" Vimball Archiver by Charles E. Campbell, Jr., Ph.D.
UseVimball
finish
autoload/atplib.vim	[[[1
685
" Title: 	Vim library for ATP filetype plugin.
" Author:	Marcin Szamotulski
" Email:	mszamot [AT] gmail [DOT] com
" Note:		This file is a part of Automatic Tex Plugin for Vim.
" URL:		https://launchpad.net/automatictexplugin
" Language:	tex

" Source ATPRC File:
function! atplib#ReadATPRC() "{{{
    if ( has("unix") || has("max") || has("macunix") )
	" Note: in $HOME/.atprc file the user can set all the local buffer
	" variables without using autocommands
	"
	" Note: it must be sourced at the begining because some options handle
	" how atp will load (for example if we load history or not)
	" It also should be run at the end if the user defines mapping that
	" should be overwrite the ATP settings (this is done via
	" autocommand).
	let atprc_file=get(split(globpath($HOME, '.atprc.vim', 1), "\n"), 0, "")
	if !filereadable(atprc_file)
	    let atprc_file = get(split(globpath(&rtp, "**/ftplugin/ATP_files/atprc.vim"), '\n'), 0, "")
	endif
	if filereadable(atprc_file)
	    execute 'source ' . fnameescape(atprc_file)
	endif
    else
	let atprc_file = get(split(globpath(&rtp, "**/ftplugin/ATP_files/atprc.vim"), '\n'), 0, "")
	if filereadable(atprc_file)
	    execute 'source ' . fnameescape(atprc_file)
	endif
    endif
endfunction "}}}
" Kill:
function! atplib#KillPIDs(pids,...) "{{{
    if len(a:pids) == 0 && a:0 == 0
	return
    endif
python << END
import os, signal
from signal import SIGKILL
pids=vim.eval("a:pids")
for pid in pids:
    try:
	os.kill(int(pid),SIGKILL)
    except OSError:
        pass
END
endfunction "}}}
" Write:
function! atplib#write(command,...) "{{{
    let time = reltime()

    let backup		= &backup
    let writebackup	= &writebackup
    let project		= b:atp_ProjectScript

    " Disable WriteProjectScript
    if a:command =~# '^\(AU\|nobackup\)$'
	set nobackup
	set nowritebackup
	" eventsignore, for example updateing tags with this BufWrite...
	" groups will be disabled.
	let eventignore	= &eventignore
	let &eventignore.=(&eventignore == "" ? "" : ",").g:atp_write_eventignore
    endif
    let b:atp_ProjectScript = 0

    let main_file = atplib#FullPath(b:atp_MainFile)
    let silent = ( a:0 ? a:1 : "" )

    " This works for single files:
    if a:0 > 0 && a:1 == "silent"
	silent! update
    else
	update
    endif
    let b:atp_changedtick = b:changedtick
    " This works for projects, but it is too slow:
"     bufdo call atplib#update(main_file, silent)

    if a:command =~# '^\(AU\|nobackup\)$'
	let &backup		= backup
	let &writebackup	= writebackup
        let &eventignore	= eventignore
    endif
    let b:atp_ProjectScript = project
    let g:time_update = reltimestr(reltime(time))
endfunction "}}}
function! atplib#update(main_file, ...) "{{{
    if !(exists("b:atp_MainFile") && a:main_file == atplib#FullPath(b:atp_MainFile))
" 	echomsg "NO UPDATE: ".expand("%:p")
	return
    endif
"     echomsg "UPDATE: ".expand("%:p")

    if a:0 > 0 && a:1 == "silent"
	silent! update
    else
	update
    endif

endfunction "}}}
" Log:
function! atplib#Log(file, string, ...) "{{{1
    if finddir(g:atp_TempDir, "/") == ""
	call mkdir(g:atp_TempDir, "p", 0700)
    endif
    if a:0 >= 1
	call delete(g:atp_TempDir."/".a:file)
    else
	exe "redir >> ".g:atp_TempDir."/".a:file 
	silent echo a:string
	redir END
    endif
endfunction "}}}1

"Make g:atp_TempDir, where log files are stored.
function! atplib#TempDir() "{{{1
    " Return temporary directory, unique for each user.
if has("python")
python << END
import vim, tempfile, os
USER=os.getenv("USER")
tmp=tempfile.mkdtemp(suffix="", prefix="atp_")
vim.command("let g:atp_TempDir='"+tmp+"'")
END
else
    let td = tempname()
    let g:atp_TempDir=substitute(td, '\d\+$', "atp_debug", '')
    call mkdir(g:atp_TempDir, "p", 0700)
endif
endfunction
"}}}1
" Outdir: append to '/' to b:atp_OutDir if it is not present. 
function! atplib#outdir() "{{{1
    if has("win16") || has("win32") || has("win64") || has("win95")
	if b:atp_OutDir !~ "\/$"
	    let b:atp_OutDir=b:atp_OutDir . "\\"
	endif
    else
	if b:atp_OutDir !~ "\/$"
	    let b:atp_OutDir=b:atp_OutDir . "/"
	endif
    endif
    return b:atp_OutDir
endfunction
"}}}1
" Return {path} relative to {rel}, if not under {rel} return {path}
function! atplib#RelativePath(path, rel) "{{{1
    let current_dir 	= getcwd()
    exe "lcd " . fnameescape(a:rel)
    let rel_path	= fnamemodify(a:path, ':.')
    exe "lcd " . fnameescape(current_dir)
    return rel_path
endfunction
"}}}1
" Return fullpath
function! atplib#FullPath(file_name) "{{{1
    let cwd = getcwd()
    if a:file_name == fnamemodify(fnamemodify(a:file_name, ":t"), ":p") 
	" if a:file_name is already a full path
        " Note: fnamemodify(a:file_name, ":p") will not return what I need if
        " a:file_name ="some_dir/file.tex"
        "
        " I should first change directory to ... to what? (i.e. before the if
        " condition).
	let file_path = a:file_name
    else
	let project_dir = ""
	if exists("b:atp_ProjectDir") && exists("b:ListOfFiles") &&
		    \ index(map(copy(b:ListOfFiles)+[b:atp_MainFile], 'fnamemodify(v:val, ":t")'), fnamemodify(a:file_name, ":t")) != -1
	    " check the current buffer.
	    let project_dir = b:atp_ProjectDir
	else
	    " else, search in all buffer variables b:ListOfFiles for the correct
	    " b:atp_ProjectDir variable.
	    for i in filter(range(1,bufnr("$")), 'bufloaded(v:val)')
		if type(getbufvar(i, "ListOfFiles")) == 3
		    if index(map(getbufvar(i, "ListOfFiles")+[getbufvar(i,"atp_MainFile")], 'fnamemodify(v:val, ":t")'), fnamemodify(a:file_name, ":t")) != -1
			let project_dir = getbufvar(i, "atp_ProjectDir")
			let bufname = bufname(i)
			break
		    endif
		endif
	    endfor
	endif
        let g:project_dir = project_dir
	if project_dir != ""
	    try
		exe "lcd " . fnameescape(project_dir)
		let file_path = fnamemodify(a:file_name, ":p")
		exe "lcd " . fnameescape(cwd)
	    catch /E344:/
		" If project_dir points to non existing path
		" this will show not the right place:
		echohl ErrorMsg
		echomsg "E344: in atplib#FullPath(): b:atp_ProjectDir=".project_dir." from buffer ".bufname." does not exist."
		echohl Normal
		let file_path = fnamemodify(a:file_name, ":p")
	    endtry
	else
	    let file_path = fnamemodify(a:file_name, ":p")
	endif
    endif
    return file_path
endfunction
"}}}1
" Table:
"{{{ atplibTable, atplib#FormatListinColumns, atplib#PrintTable
function! atplib#Table(list, spaces)
" take a list of lists and make a list which is nicely formated (to echo it)
" spaces = list of spaces between columns.
    "maximal length of columns:
    let max_list=[]
    let new_list=[]
    for i in range(len(a:list[0]))
	let max=max(map(deepcopy(a:list), "len(v:val[i])"))
	call add(max_list, max)
    endfor

    for row in a:list
	let new_row=[]
	let i=0
	for el in row
	    let new_el=el.join(map(range(max([0,max_list[i]-len(el)+get(a:spaces,i,0)])), "' '"), "")
	    call add(new_row, new_el)
	    let i+=1
	endfor
	call add(new_list, new_row)
    endfor

    return map(new_list, "join(v:val, '')")
endfunction 
function! atplib#FormatListinColumns(list,s)
    " take a list and reformat it into many columns
    " a:s is the number of spaces between columns
    " for example of usage see atplib#PrintTable
    let max_len=max(map(copy(a:list), 'len(v:val)'))
    let new_list=[]
    let k=&l:columns/(max_len+a:s)
    let len=len(a:list)
    let column_len=len/k
    for i in range(0, column_len)
	let entry=[]
	for j in range(0,k)
	    call add(entry, get(a:list, i+j*(column_len+1), ""))
	endfor
	call add(new_list,entry)
    endfor
    return new_list
endfunction 
" Take list format it with atplib#FormatListinColumns and then with
" atplib#Table (which makes columns of equal width)
function! atplib#PrintTable(list, spaces)
    " a:list 	- list to print
    " a:spaces 	- nr of spaces between columns 

    let list = atplib#FormatListinColumns(a:list, a:spaces)
    let nr_of_columns = max(map(copy(list), 'len(v:val)'))
    let spaces_list = ( nr_of_columns == 1 ? [0] : map(range(1,nr_of_columns-1), 'a:spaces') )

    return atplib#Table(list, spaces_list)
endfunction
"}}}

function! atplib#qflength() "{{{
    let lines = 1
    " i.e. open with one more line than needed.
    for qf in getqflist()
	let text=substitute(qf['text'], '\_s\+', ' ', 'g')
	let lines+=(len(text))/&l:columns+1
    endfor
    return lines
endfunction "}}}

function! atplib#Let(varname, varvalue) "{{{
    exe "let ".substitute(string(a:varname), "'", "", "g")."=".substitute(string(a:varvalue), "''\\@!", "", "g")
endfunction "}}}

" IMap Functions:
" {{{
" These maps extend ideas from TeX_9 plugin:
" With a:1 = "!" (bang) remove texMathZoneT (tikzpicture from MathZones).
function! atplib#IsInMath(...)
    let line		= a:0 >= 2 ? a:2 : line(".")
    let col		= a:0 >= 3 ? a:3 : col(".")-1
    if a:0 > 0 && a:1 == "!"
	let atp_MathZones=filter(copy(g:atp_MathZones), "v:val != 'texMathZoneT'")
    else
	let atp_MathZones=copy(g:atp_MathZones)
    endif
    call filter(atp_MathZones, 'v:val !~ ''\<texMathZone[VWXY]\>''')
    if atplib#complete#CheckSyntaxGroups(['texMathZoneV', 'texMathZoneW', 'texMathZoneX', 'texMathZoneY'])
	return 1
    else
	return atplib#complete#CheckSyntaxGroups(atp_MathZones, line, col) && 
		    \ !atplib#complete#CheckSyntaxGroups(['texMathText'], line, col)
    endif
endfunction
function! atplib#MakeMaps(maps, ...)
    let aucmd = ( a:0 >= 1 ? a:1 : '' )
    for map in a:maps
	if map[3] != "" && ( !exists(map[5]) || {map[5]} > 0 || 
		    \ exists(map[5]) && {map[5]} == 0 && aucmd == 'InsertEnter'  )
	    if exists(map[5]) && {map[5]} == 0 && aucmd == 'InsertEnter'
		exe "let ".map[5]." =1"
	    endif
	    exe map[0]." ".map[1]." ".map[2].map[3]." ".map[4]
	endif
    endfor
endfunction
function! atplib#DelMaps(maps)
    for map in a:maps
	let cmd = matchstr(map[0], '[^m]\ze\%(nore\)\=map') . "unmap"
	let arg = ( map[1] =~ '<buffer>' ? '<buffer>' : '' )
	try
	    exe cmd." ".arg." ".map[2].map[3]
	catch /E31:/
	endtry
    endfor
endfunction
" From TeX_nine plugin:
function! atplib#IsLeft(lchar,...)
    let nr = ( a:0 >= 1 ? a:1 : 0 )
    let left = getline('.')[col('.')-2-nr]
    if left ==# a:lchar
	return 1
    else
	return 0
    endif
endfunction
" try
function! atplib#ToggleIMaps(var, augroup, ...)
    if exists("s:isinmath") && 
		\ ( atplib#IsInMath() == s:isinmath ) &&
		\ ( a:0 >= 2 && a:2 ) &&
		\ a:augroup == 'CursorMovedI'
	return
    endif

    call SetMathVimOptions()

    if atplib#IsInMath() 
	call atplib#MakeMaps(a:var, a:augroup)
    else
	call atplib#DelMaps(a:var)
	if a:0 >= 1 && len(a:1)
	    call atplib#MakeMaps(a:1)
	endif
    endif
    let s:isinmath = atplib#IsInMath() 
endfunction
" catch E127
" endtry "}}}

" Toggle on/off Completion 
" {{{1 atplib#OnOffComp
function! atplib#OnOffComp(ArgLead, CmdLine, CursorPos)
    return filter(['on', 'off'], 'v:val =~ "^" . a:ArgLead') 
endfunction
"}}}1
" Toggle on/off/local Completion 
" {{{1 atplib#OnOffComp
function! atplib#OnOffLocalComp(ArgLead, CmdLine, CursorPos)
    return filter(['on', 'off', 'local'], 'v:val =~ "^" . a:ArgLead') 
endfunction
"}}}1

" Find Vim Server: find server 'hosting' a file and move to the line.
" {{{1 atplib#FindAndOpen
" Can be used to sync gvim with okular.
" just set in okular:
" 	settings>okular settings>Editor
" 		Editor		Custom Text Editor
" 		Command		gvim --servername GVIM --remote-expr "atplib#FindAndOpen('%f','%l', '%c')"
" You can also use this with vim but you should start vim with
" 		vim --servername VIM
" and use servername VIM in the Command above.		
function! atplib#ServerListOfFiles()
    exe "redir! > " . g:atp_TempDir."/ServerListOfFiles.log"
    let file_list = []
    for nr in range(1, bufnr('$'))
	" map fnamemodify(v:val, ":p") is not working if we are in another
	" window with file in another dir. So we are not using this (it might
	" happen that we end up in a wrong server though).
	if exists("main_file")
	    unlet main_file
	endif
	let main_file 	= getbufvar(nr, "atp_MainFile")
	let log_file	= ( expand("%:e") =~# '^_\?log$' )
	if exists("files")
	    unlet files
	endif
	let files 	= getbufvar(nr, "ListOfFiles")
	if string(main_file) != "" && !log_file
	    call add(file_list, main_file)
	endif
	if type(files) == 3 && !log_file
	    call extend(file_list, files)
	endif
    endfor
    call filter(file_list, 'v:val != ""')
    redir end
    return file_list
endfunction
function! atplib#FindAndOpen(file, output_file, line, ...)
    let col		= ( a:0 >= 1 && a:1 > 0 ? a:1 : 1 )
    let file		= ( fnamemodify(simplify(a:file), ":e") == "tex" ? simplify(a:file) : fnamemodify(simplify(a:file), ":p:r") . ".tex" )
    let file_t		= fnamemodify(file, ":t")
    let main_file	= ( fnamemodify(simplify(a:output_file), ":e") == "tex" ? simplify(a:output_file) : fnamemodify(simplify(a:output_file), ":p:r") . ".tex" )
    let main_file_t	= fnamemodify(file, ":t")
    let server_list	= split(serverlist(), "\n")
    exe "redir! > /tmp/FindAndOpen.log"
    if len(server_list) == 0
	return 1
    endif
    let open		= "buffer"
    let use_server	= ""
    let use_servers	= []
    for server in server_list
	let file_list=split(remote_expr(server, 'atplib#ServerListOfFiles()'), "\n")
	" Note: atplib#ServerListOfFiles returns all the files loaded by the
	" server plus all corresponding values of b:ListOfFiles
	let cond_1 = (index(file_list, file) != "-1")
	let cond_2 = (index(file_list, file_t) != "-1")
	if cond_1
	    let use_server	= server
	    break
	elseif cond_2
	    call add(use_servers, server)
	endif
    endfor
    " If we could not find file name with full path in server list use the
    " first server where is fnamemodify(file, ":t"). 
    if use_server == ""
	let use_server=get(use_servers, 0, "")
    endif
    if use_server != ""
	if !remote_expr(use_server, 'bufloaded("'.file.'")')
	    " Change the jump list by setting the ' mark:
	    call remote_send(user_server, "<Esc>:mark `<CR>")
	    call system(v:progname." --servername ".use_server." --remote-wait +".a:line." ".fnameescape(file) . " &")
	else
	    " Test this for file names with spaces
	    let bufwinnr 	= remote_expr(use_server, 'bufwinnr("'.file.'")')
	    let bufnr		= remote_expr(use_server, "bufnr('".file."')")
	    if bufwinnr 	== "-1"
 	    " The buffer is in a different tab page.
		let tabpage	= 0
 	    " Find the correct tabpage:
		for tabnr in range(1, remote_expr(use_server, 'tabpagenr("$")'))
		    let tabbuflist = split(remote_expr(use_server, 'tabpagebuflist("'.tabnr.'")'), "\n")
		    let tabbuflist_names = split(remote_expr(use_server, 'map(tabpagebuflist("'.tabnr.'"), "bufname(v:val)")'), "\n")
		    if count(tabbuflist_names, file) || count(tabfublist_names, file_t)
			let tabpage = tabnr
			break
		    endif
		endfor
		" Goto to the tabpage:
		if tabpage && remote_expr(use_server, 'tabpagenr()') != tabpage
		    call remote_send(use_server, '<Esc>:tabnext '.tabpage.'<CR>')
		elseif !tabpage
		    " The file is not present in any file, but the buffer is
		    " loaded.
		    call remote_send(use_server, '<Esc>:buffer '.bufnr)
		endif
		" Check the bufwinnr once again:
		let bufwinnr 	= remote_expr(use_server, 'bufwinnr("'.file.'")')
	    endif

	    " winnr() doesn't work remotely, this is a substitute:
	    let remote_file = remote_expr(use_server, 'expand("%:t")')
	    if string(remote_file) != string(file_t)
		if bufwinnr != -1
		    call remote_send(use_server, "<Esc>:".bufwinnr."wincmd w<CR>")
		else
		    call remote_send(use_server, "<Esc>:buffer ".bufnr."<CR>")
		endif
	    endif
	    " Change the jump list by setting the ' mark:
	    call remote_send(use_server, "<Esc>:mark `<CR>")
	    " Set the ' mark (jump list), cursor position and redraw:
	    call remote_send(use_server, "<Esc>:call cursor(".a:line.",".col.")<CR>:redraw<CR>")
	endif
    endif
    return use_server
endfunction
"}}}1

" Various Comparing Functions:
"{{{1 atplib#CompareNumbers
function! atplib#CompareNumbers(i1, i2)
   return ( str2nr(a:i1) == str2nr(a:i2) ? 0 : ( str2nr(a:i1) > str2nr(a:i2) ? 1 : -1 ) )
endfunction
"}}}1
" {{{1 atplib#CompareCoordinates
" Each list is an argument with two values:
" listA=[ line_nrA, col_nrA] usually given by searchpos() function
" listB=[ line_nrB, col_nrB]
" returns 1 iff A is before B
fun! atplib#CompareCoordinates(listA,listB)
    if a:listA[0] < a:listB[0] || 
	\ a:listA[0] == a:listB[0] && a:listA[1] < a:listB[1] ||
	\ a:listA == [0,0]
	" the meaning of the last is that if the searchpos() has not found the
	" beginning (a:listA) then it should return 1 : the env is not started.
	return 1
    else
	return 0
    endif
endfun
"}}}1
" {{{1 atplib#CompareCoordinates_leq
" Each list is an argument with two values!
" listA=[ line_nrA, col_nrA] usually given by searchpos() function
" listB=[ line_nrB, col_nrB]
" returns 1 iff A is smaller or equal to B
function! atplib#CompareCoordinates_leq(listA,listB)
    if a:listA[0] < a:listB[0] || 
	\ a:listA[0] == a:listB[0] && a:listA[1] <= a:listB[1] ||
	\ a:listA == [0,0]
	" the meaning of the last is that if the searchpos() has not found the
	" beginning (a:listA) then it should return 1 : the env is not started.
	return 1
    else
	return 0
    endif
endfunction
"}}}1
" {{{1 atplib#CompareStarAfter
" This is used by atplib#complete#TabCompletion to put abbreviations of starred environment after not starred version
function! atplib#CompareStarAfter(i1, i2)
    if a:i1 !~ '\*' && a:i2 !~ '\*'
	if a:i1 == a:i2
	    return 0
	elseif a:i1 < a:i2
	    return -1
	else
	    return 1
	endif
    else
	let i1 = substitute(a:i1, '\*', '', 'g')
	let i2 = substitute(a:i2, '\*', '', 'g')
	if i1 == i2
	    if a:i1 =~ '\*' && a:i2 !~ '\*'
		return 1
	    else
		return -1
	    endif
	    return 0
	elseif i1 < i2
	    return -1
	else
	    return 1
	endif
    endif
endfunction
" }}}1

" ReadInputFile function reads finds a file in tex style and returns the list
" of its lines. 
" {{{1 atplib#ReadInputFile
" this function looks for an input file: in the list of buffers, under a path if
" it is given, then in the b:atp_OutDir.
" directory. The last argument if equal to 1, then look also
" under g:texmf.
function! atplib#ReadInputFile(ifile,check_texmf)

    let l:input_file = []

    " read the buffer or read file if the buffer is not listed.
    if buflisted(fnamemodify(a:ifile,":t"))
	let l:input_file=getbufline(fnamemodify(a:ifile,":t"),1,'$')
    " if the ifile is given with a path it should be tried to read from there
    elseif filereadable(a:ifile)
	let l:input_file=readfile(a:ifile)
    " if not then try to read it from b:atp_OutDir
    elseif filereadable(b:atp_OutDir . fnamemodify(a:ifile,":t"))
	let l:input_file=readfile(filereadable(b:atp_OutDir . fnamemodify(a:ifile,":t")))
    " the last chance is to look for it in the g:texmf directory
    elseif a:check_texmf && filereadable(findfile(a:ifile,g:texmf . '**'))
	let l:input_file=readfile(findfile(a:ifile,g:texmf . '**'))
    endif

    return l:input_file
endfunction
"}}}1

" URL query: (by some strange reason this is not working moved to url_query.py)
" function! atplib#URLquery(url) "{{{
" python << EOF
" import urllib2, tempfile, vim
" url  = vim.eval("a:url") 
" print(url)
" temp = tempfile.mkstemp("", "atp_ams_")
" 
" f    = open(temp[1], "w+")
" data = urllib2.urlopen(url)
" f.write(data.read())
" vim.command("return '"+temp[1]+"'")
" EOF
" endfunction "}}}

" This function sets the window options common for toc and bibsearch windows.
"{{{1 atplib#setwindow
" this function sets the options of BibSearch, ToC and Labels windows.
function! atplib#setwindow()
" These options are set in the command line
" +setl\\ buftype=nofile\\ filetype=bibsearch_atp   
" +setl\\ buftype=nofile\\ filetype=toc_atp\\ nowrap
" +setl\\ buftype=nofile\\ filetype=toc_atp\\ syntax=labels_atp
	setlocal nonumber
	setlocal norelativenumber
 	setlocal winfixwidth
	setlocal noswapfile	
	setlocal nobuflisted
	if &filetype == "bibsearch_atp"
" 	    setlocal winwidth=30
	    setlocal nospell
	endif
" 	nnoremap <expr> <buffer> <C-W>l	"keepalt normal l"
" 	nnoremap <buffer> <C-W>h	"keepalt normal h"
endfunction
" }}}1
" {{{1 atplib#count
function! atplib#count(line, keyword,...)
   
    let method = ( a:0 == 0 || a:1 == 0 ) ? 0 : 1

    let line=a:line
    let i=0  
    if method==0
	while stridx(line, a:keyword) != '-1'
	    let line	= strpart(line, stridx(line, a:keyword)+1)
	    let i +=1
	endwhile
    elseif method==1
	let pat = a:keyword.'\zs'
	while line =~ pat
	    let line	= strpart(line, match(line, pat))
	    let i +=1
	endwhile
    endif
    return i
endfunction
" }}}1
" Used to append / at the end of a directory name
" {{{1 atplib#append 	
fun! atplib#append(where, what)
    return substitute(a:where, a:what . '\s*$', '', '') . a:what
endfun
" }}}1
" Used to append extension to a file name (if there is no extension).
" {{{1 atplib#append_ext 
" extension has to be with a dot.
fun! atplib#append_ext(fname, ext)
    return substitute(a:fname, a:ext . '\s*$', '', '') . a:ext
endfun
" }}}1

" List Functions:
" atplib#Extend {{{1
" arguments are the same as for extend(), but it adds only the entries which
" are not present.
function! atplib#Extend(list_a,list_b,...)
    let list_a=deepcopy(a:list_a)
    let list_b=deepcopy(a:list_b)
    let diff=filter(list_b,'count(l:list_a,v:val) == 0')
    if a:0 == 0
	return extend(list_a,diff)
    else
	return extend(list_a,diff, a:1)
    endif
endfunction
" }}}1
" {{{1 atplib#Add
function! atplib#Add(list,what)
    let new=[] 
    for element in a:list
	call add(new,element . a:what)
    endfor
    return new
endfunction
"}}}1
" vim:fdm=marker:ff=unix:noet:ts=8:sw=4:fdc=1
autoload/atplib/bibsearch.vim	[[[1
817
" Title: 	Vim library for ATP filetype plugin.
" Author:	Marcin Szamotulski
" Email:	mszamot [AT] gmail [DOT] com
" Note:		This file is a part of Automatic Tex Plugin for Vim.
" URL:		https://launchpad.net/automatictexplugin
" Language:	tex
" Last Modified: 

" BIB SEARCH:
" These are all bibsearch related variables and functions.
"{{{ atplib#bibsearch#variables
let atplib#bibsearch#bibflagsdict={ 
                \ 't' : ['title',       'title        '],               'a' : ['author',        'author       '], 
		\ 'b' : ['booktitle',   'booktitle    '],               'c' : ['mrclass',       'mrclass      '], 
		\ 'e' : ['editor',      'editor       '], 	        'j' : ['journal',       'journal      '], 
		\ 'f' : ['fjournal',    'fjournal     '], 	        'y' : ['year',          'year         '], 
		\ 'n' : ['number',      'number       '], 	        'v' : ['volume',        'volume       '], 
		\ 's' : ['series',      'series       '], 	        'p' : ['pages',         'pages        '], 
		\ 'P' : ['publisher',   'publisher    '],               'N' : ['note',          'note         '], 
		\ 'S' : ['school',      'school       '], 	        'h' : ['howpublished',  'howpublished '], 
		\ 'o' : ['organization', 'organization '],              'I' : ['institution' ,  'institution '],
		\ 'u' : ['url',         'url          '],
		\ 'H' : ['homepage',    'homepage     '], 	        'i' : ['issn',          'issn         '],
		\ 'k' : ['key',         'key          '], 	        'R' : ['mrreviewer',    'mrreviewer   ']}
" they do not work in the library script :(
" using g:bibflags... .
" let atplib#bibflagslist=keys(atplib#bibsearch#bibflagsdict)
" let atplib#bibflagsstring=join(atplib#bibflagslist,'')
"}}}
"{{{ atplib#bibsearch#searchbib
" This is the main search engine.
" ToDo should not search in comment lines.

" To make it work after kpsewhich is searching for bib path.
" let s:bibfiles=FindBibFiles(bufname('%'))
function! atplib#bibsearch#searchbib(pattern, bibdict, ...) 

    call atplib#outdir()
    " for tex files this should be a flat search.
    let flat 	= &filetype == "plaintex" ? 1 : 0
    let bang	= a:0 >=1 ? a:1 : ""
    let atp_MainFile	= atplib#FullPath(b:atp_MainFile)

    " Make a pattern which will match for the elements of the list g:bibentries
    let pattern = '^\s*@\%(\<'.g:bibentries[0].'\>'
    for bibentry in g:bibentries['1':len(g:bibentries)]
	let pattern	= pattern . '\|\<' . bibentry . '\>'
    endfor
    let pattern	= pattern . '\)'
" This pattern matches all entry lines: author = \| title = \| ... 
    let pattern_b = '^\s*\%('
    for bibentry in keys(g:bibflagsdict)
	let pattern_b	= pattern_b . '\|\<' . g:bibflagsdict[bibentry][0] . '\>'
    endfor
    let pattern_b.='\)\s*='

    if g:atp_debugBS
	exe "redir! >>".g:atp_TempDir."/BibSearch.log"
	silent! echo "==========atplib#bibsearch#searchbib==================="
	silent! echo "atplib#bibsearch#searchbib_bibfiles=" . string(s:bibfiles)
	silent! echo "a:pattern=" . a:pattern
	silent! echo "pattern=" . pattern
	silent! echo "pattern_b=" . pattern_b
	silent! echo "bang=" . bang
	silent! echo "flat=" . flat
    endif

    unlet bibentry
    let b:bibentryline={} 
    
    " READ EACH BIBFILE IN TO DICTIONARY s:bibdict, WITH KEY NAME BEING THE bibfilename
    let s:bibdict={}
    let l:bibdict={}
    for l:f in keys(a:bibdict)
	let s:bibdict[l:f]=[]

	" read the bibfile if it is in b:atp_OutDir or in g:atp_raw_bibinputs directory
	" ToDo: change this to look in directories under g:atp_raw_bibinputs. 
	" (see also ToDo in FindBibFiles 284)
" 	for l:path in split(g:atp_raw_bibinputs, ',') 
" 	    " it might be problem when there are multiple libraries with the
" 	    " same name under different locations (only the last one will
" 	    " survive)
" 	    let s:bibdict[l:f]=readfile(fnameescape(findfile(atplib#append(l:f,'.bib'), atplib#append(l:path,"/") . "**")))
" 	endfor
	let l:bibdict[l:f]=copy(a:bibdict[l:f])
	" clear the s:bibdict values from lines which begin with %    
	call filter(l:bibdict[l:f], ' v:val !~ "^\\s*\\%(%\\|@\\cstring\\)"')
    endfor

    if g:atp_debugBS
	silent! echo "values(l:bibdict) len(l:bibdict[v:val]) = " . string(map(deepcopy(l:bibdict), "len(v:val)"))
    endif

    if a:pattern != ""
	for l:f in keys(a:bibdict)
	    let l:list=[]
	    let l:nr=1
	    for l:line in l:bibdict[l:f]
		" Match Pattern:
		" if the line matches find the beginning of this bib field and add its
		" line number to the list l:list
		" remove ligatures and brackets {,} from the line
		let line_without_ligatures = substitute(substitute(l:line,'\C{\|}\|\\\%("\|`\|\^\|=\|\.\|c\|\~\|v\|u\|d\|b\|H\|t\)\s*','','g'), "\\\\'\\s*", '', 'g')
		let line_without_ligatures = substitute(line_without_ligatures, '\C\\oe', 'oe', 'g')
		let line_without_ligatures = substitute(line_without_ligatures, '\C\\OE', 'OE', 'g')
		let line_without_ligatures = substitute(line_without_ligatures, '\C\\ae', 'ae', 'g')
		let line_without_ligatures = substitute(line_without_ligatures, '\C\\AE', 'AE', 'g')
		let line_without_ligatures = substitute(line_without_ligatures, '\C\\o', 'o', 'g')
		let line_without_ligatures = substitute(line_without_ligatures, '\C\\O', 'O', 'g')
		let line_without_ligatures = substitute(line_without_ligatures, '\C\\i', 'i', 'g')
		let line_without_ligatures = substitute(line_without_ligatures, '\C\\j', 'j', 'g')
		let line_without_ligatures = substitute(line_without_ligatures, '\C\\l', 'l', 'g')
		let line_without_ligatures = substitute(line_without_ligatures, '\C\\L', 'L', 'g')

		if line_without_ligatures =~? a:pattern

		    if g:atp_debugBS
			silent! echo "line_without_ligatures that matches " . line_without_ligatures
			silent! echo "____________________________________"
		    endif

		    let l:true=1
		    let l:t=0
		    while l:true == 1
			let l:tnr=l:nr-l:t

			    if g:atp_debugBS
				silent! echo " l:tnr=" . string(l:tnr) . " l:bibdict[". string(l:f) . "][" . string(l:tnr-1) . "]=" . string(l:bibdict[l:f][l:tnr-1])
			    endif

			" go back until the line will match pattern (which
			" should be the beginning of the bib field.
		       if l:bibdict[l:f][l:tnr-1] =~? pattern && l:tnr >= 0
			   let l:true=0
			   let l:list=add(l:list,l:tnr)
		       elseif l:tnr <= 0
			   let l:true=0
		       endif
		       let l:t+=1
		    endwhile
		endif
		let l:nr+=1
	    endfor

	    if g:atp_debugBS
		silent! echo "A l:list=" . string(l:list)
	    endif

    " CLEAR THE l:list FROM ENTRIES WHICH APPEAR TWICE OR MORE --> l:clist
	    let l:pentry="A"		" We want to ensure that l:entry (a number) and l:pentry are different
	    for l:entry in l:list
		if l:entry != l:pentry
		    if count(l:list,l:entry) > 1
			while count(l:list,l:entry) > 1
			    let l:eind=index(l:list,l:entry)
			    call remove(l:list,l:eind)
			endwhile
		    endif 
		    let l:pentry=l:entry
		endif
	    endfor

	    " This is slower than the algorithm above! 
" 	    call sort(filter(l:list, "count(l:list, v:val) == 1"), "atplib#CompareNumbers")

	    if g:atp_debugBS
		silent! echo "B l:list=" . string(l:list)
	    endif

	    let b:bibentryline=extend(b:bibentryline,{ l:f : l:list })

	    if g:atp_debugBS
		silent! echo "atplib#bibsearch b:bibentryline= (pattern != '') " . string(b:bibentryline)
	    endif

	endfor
    endif
"   CHECK EACH BIBFILE
    let l:bibresults={}
"     if the pattern was empty make it faster. 
    if a:pattern == ""
	for l:bibfile in keys(l:bibdict)
	    let l:bibfile_len=len(l:bibdict[l:bibfile])
	    let s:bibd={}
		let l:nr=0
		while l:nr < l:bibfile_len
		    let l:line=l:bibdict[l:bibfile][l:nr]
		    if l:line =~ pattern
			let s:lbibd={}
			let s:lbibd["bibfield_key"]=l:line
			let l:beg_line=l:nr+1
			let l:nr+=1
			let l:line=l:bibdict[l:bibfile][l:nr]
			let l:y=1
			while l:line !~ pattern && l:nr < l:bibfile_len
			    let l:line=l:bibdict[l:bibfile][l:nr]
			    let l:lkey=tolower(
					\ matchstr(
					    \ strpart(l:line,0,
						\ stridx(l:line,"=")
					    \ ),'\<\w*\>'
					\ ))
	" CONCATENATE LINES IF IT IS NOT ENDED
			    let l:y=1
			    if l:lkey != ""
				let s:lbibd[l:lkey]=l:line
	" IF THE LINE IS SPLIT ATTACH NEXT LINE									
				let l:nline=get(l:bibdict[l:bibfile],l:nr+l:y)
				while l:nline !~ '=' && 
					    \ l:nline !~ pattern &&
					    \ (l:nr+l:y) < l:bibfile_len
				    let s:lbibd[l:lkey]=substitute(s:lbibd[l:lkey],'\s*$','','') . " ". substitute(get(l:bibdict[l:bibfile],l:nr+l:y),'^\s*','','')
				    let l:line=get(l:bibdict[l:bibfile],l:nr+l:y)
				    let l:y+=1
				    let l:nline=get(l:bibdict[l:bibfile],l:nr+l:y)
				    if l:y > 30
					echoerr "ATP-Error /see :h atp-errors-bibsearch/, missing '}', ')' or '\"' in bibentry (check line " . l:nr . ") in " . l:f . " line=".l:line
					break
				    endif
				endwhile
				if l:nline =~ pattern 
				    let l:y=1
				endif
			    endif
			    let l:nr+=l:y
			    unlet l:y
			endwhile
			let l:nr-=1
			call extend(s:bibd, { l:beg_line : s:lbibd })
		    else
			let l:nr+=1
		    endif
		endwhile
	    let l:bibresults[l:bibfile]=s:bibd
	endfor

	if g:atp_debugBS
	    silent! echo "atplib#bibsearch#searchbib_bibresults A =" . l:bibresults
	endif

	return l:bibresults
    endif
    " END OF NEW CODE: (up)

    for l:bibfile in keys(b:bibentryline)
	let l:f=l:bibfile . ".bib"
"s:bibdict[l:f])	CHECK EVERY STARTING LINE (we are going to read bibfile from starting
"	line till the last matching } 
 	let s:bibd={}
 	for l:linenr in b:bibentryline[l:bibfile]

	    let l:nr=l:linenr-1
	    let l:i=atplib#count(get(l:bibdict[l:bibfile],l:linenr-1),"{")-atplib#count(get(l:bibdict[l:bibfile],l:linenr-1),"}")
	    let l:j=atplib#count(get(l:bibdict[l:bibfile],l:linenr-1),"(")-atplib#count(get(l:bibdict[l:bibfile],l:linenr-1),")") 
	    let s:lbibd={}
	    let s:lbibd["bibfield_key"]=get(l:bibdict[l:bibfile],l:linenr-1)
	    if s:lbibd["bibfield_key"] !~ '@\w\+\s*{.\+' 
		let l:l=0
		while get(l:bibdict[l:bibfile],l:linenr-l:l) =~ '^\s*$'
		    let l:l+=1
		endwhile
		let s:lbibd["bibfield_key"] .= get(l:bibdict[l:bibfile],l:linenr+l:l)
		let s:lbibd["bibfield_key"] = substitute(s:lbibd["bibfield_key"], '\s', '', 'g')
	    endif

	    let l:x=1
" we go from the first line of bibentry, i.e. @article{ or @article(, until the { and (
" will close. In each line we count brackets.	    
            while l:i>0	|| l:j>0
		let l:tlnr=l:x+l:linenr
		let l:pos=atplib#count(get(l:bibdict[l:bibfile],l:tlnr-1),"{")
		let l:neg=atplib#count(get(l:bibdict[l:bibfile],l:tlnr-1),"}")
		let l:i+=l:pos-l:neg
		let l:pos=atplib#count(get(l:bibdict[l:bibfile],l:tlnr-1),"(")
		let l:neg=atplib#count(get(l:bibdict[l:bibfile],l:tlnr-1),")")
		let l:j+=l:pos-l:neg
		let l:lkey=tolower(
			    \ matchstr(
				\ strpart(get(l:bibdict[l:bibfile],l:tlnr-1),0,
				    \ stridx(get(l:bibdict[l:bibfile],l:tlnr-1),"=")
				\ ),'\<\w*\>'
			    \ ))
		if l:lkey != ""
		    let s:lbibd[l:lkey]=get(l:bibdict[l:bibfile],l:tlnr-1)
			let l:y=0
" IF THE LINE IS SPLIT ATTACH NEXT LINE									
			if get(l:bibdict[l:bibfile],l:tlnr-1) !~ '\%()\|}\|"\)\s*,\s*\%(%.*\)\?$'
" 				    \ get(l:bibdict[l:bibfile],l:tlnr) !~ pattern_b
			    let l:lline=substitute(get(l:bibdict[l:bibfile],l:tlnr+l:y-1),'\\"\|\\{\|\\}\|\\(\|\\)','','g')
			    let l:pos=atplib#count(l:lline,"{")
			    let l:neg=atplib#count(l:lline,"}")
			    let l:m=l:pos-l:neg
			    let l:pos=atplib#count(l:lline,"(")
			    let l:neg=atplib#count(l:lline,")")
			    let l:n=l:pos-l:neg
			    let l:o=atplib#count(l:lline,"\"")
    " this checks if bracets {}, and () and "" appear in pairs in the current line:  
			    if l:m>0 || l:n>0 || l:o>l:o/2*2 
				while l:m>0 || l:n>0 || l:o>l:o/2*2 
				    let l:pos=atplib#count(get(l:bibdict[l:bibfile],l:tlnr+l:y),"{")
				    let l:neg=atplib#count(get(l:bibdict[l:bibfile],l:tlnr+l:y),"}")
				    let l:m+=l:pos-l:neg
				    let l:pos=atplib#count(get(l:bibdict[l:bibfile],l:tlnr+l:y),"(")
				    let l:neg=atplib#count(get(l:bibdict[l:bibfile],l:tlnr+l:y),")")
				    let l:n+=l:pos-l:neg
				    let l:o+=atplib#count(get(l:bibdict[l:bibfile],l:tlnr+l:y),"\"")
    " Let's append the next line: 
				    let s:lbibd[l:lkey]=substitute(s:lbibd[l:lkey],'\s*$','','') . " ". substitute(get(l:bibdict[l:bibfile],l:tlnr+l:y),'^\s*','','')
				    let l:y+=1
				    if l:y > 30
					echoerr "ATP-Error /see :h atp-errors-bibsearch/, missing '}', ')' or '\"' in bibentry at line " . l:linenr . " (check line " . l:tlnr . ") in " . l:f)
					break
				    endif
				endwhile
			    endif
			endif
		endif
" we have to go line by line and we could skip l:y+1 lines, but we have to
" keep l:m, l:o values. It do not saves much.		
		let l:x+=1
		if l:x > 30
			echoerr "ATP-Error /see :h atp-errors-bibsearch/, missing '}', ')' or '\"' in bibentry at line " . l:linenr . " in " . l:f
			break
	        endif
		let b:x=l:x
		unlet l:tlnr
	    endwhile
	    
	    let s:bibd[l:linenr]=s:lbibd
	    unlet s:lbibd
	endfor
	let l:bibresults[l:bibfile]=s:bibd
    endfor

    if g:atp_debugBS
	silent! echo "atplib#bibsearch#searchbib_bibresults A =" . string(l:bibresults)
	redir END
    endif

    return l:bibresults
endfunction
"}}}
" {{{ atplib#bibsearch#searchbib_py
function! atplib#bibsearch#searchbib_py(pattern, bibfiles, ...)
    call atplib#outdir()
    " for tex files this should be a flat search.
    let flat 	= &filetype == "plaintex" ? 1 : 0
    let bang	= a:0 >=1 ? a:1 : ""
    let atp_MainFile	= atplib#FullPath(b:atp_MainFile)

    let b:atp_BibFiles=a:bibfiles
python << END
import vim, re

files=vim.eval("b:atp_BibFiles")

def remove_ligatures(string):
    line_without_ligatures = re.sub( "\\\\'\s*", '', re.sub('{|}|\\\\(?:"|`|\^|=|\.|c|~|v|u|d|b|H|t)\s*', '', string))
    line_without_ligatures = re.sub('\\\\oe', 'oe', line_without_ligatures)
    line_without_ligatures = re.sub('\\\\OE', 'OE', line_without_ligatures)
    line_without_ligatures = re.sub('\\\\ae', 'ae', line_without_ligatures)
    line_without_ligatures = re.sub('\\\\AE', 'AE', line_without_ligatures)
    line_without_ligatures = re.sub('\\\\o', 'o', line_without_ligatures)
    line_without_ligatures = re.sub('\\\\O', 'O', line_without_ligatures)
    line_without_ligatures = re.sub('\\\\i', 'i', line_without_ligatures)
    line_without_ligatures = re.sub('\\\\j', 'j', line_without_ligatures)
    line_without_ligatures = re.sub('\\\\l', 'l', line_without_ligatures)
    line_without_ligatures = re.sub('\\\\L', 'L', line_without_ligatures)
    return line_without_ligatures

def remove_quotes(string):
    line=re.sub("'", "\"", string)
    line=re.sub('\\\\', '', line)
    return line
type_pattern=re.compile('\s*@(article|book|mvbook|inbook|bookinbook|suppbook|booklet|collection|mvcollection|incollection|suppcollection|manual|misc|online|patent|periodical|supppertiodical|proceedings|mvproceedings|inproceedings|reference|mvreference|inreference|report|set|thesis|unpublished|custom[a-f]|conference|electronic|masterthesis|phdthesis|techreport|www)', re.I)

# types=['abstract', 'addendum', 'afterword', 'annotation', 'author', 'authortype', 'bookauthor', 'bookpaginator', 'booksupbtitle', 'booktitle', 'booktitleaddon', 'chapter', 'commentator', 'date', 'doi', 'edition', 'editor', 'editora', 'editorb', 'editorc', 'editortype', 'editoratype', 'editorbtype', 'editorctype', 'eid', 'eprint', 'eprintclass', 'eprinttype', 'eventdate', 'eventtile', 'file', 'forword', 'holder', 'howpublished', 'indxtitle', 'institution', 'introduction', 'isan', 'isbn', 'ismn', 'isrn', 'issn', 'issue', 'issuesubtitle', 'issuetitle', 'iswc', 'journalsubtitle', 'journaltitle', 'label', 'language', 'library', 'location', 'mainsubtitle', 'maintitle', 'maintitleaddon', 'month', 'nameaddon', 'note', 'number', 'organization', 'origdate', 'origlanguage', 'origpublisher', 'origname', 'pages', 'pagetotal', 'pagination', 'part', 'publisher', 'pubstate', 'reprinttitle', 'series', 'shortauthor', 'shorteditor', 'shorthand', 'shorthandintro', 'shortjournal', 'shortseries', 'subtitle', 'title', 'titleaddon', 'translator', 'type', 'url', 'urldate', 'venue', 'version', 'volume', 'volumes', 'year', 'crossref', 'entryset', 'entrysubtype', 'execute', 'mrreviewer']

types=['author', 'bookauthor', 'booktitle', 'date', 'editor', 'eprint', 'eprintclass', 'eprinttype', 'howpublished', 'institution', 'journal', 'month', 'note', 'number', 'organization', 'pages', 'publisher', 'school', 'series', 'subtitle', 'title', 'url', 'year', 'mrreviewer', 'volume', 'pages']

def parse_bibentry(bib_entry):
    bib={}
    bib['bibfield_key']=re.sub('\\r$', '', bib_entry[0])
    nr=1
    while nr < len(bib_entry)-1:
        line=bib_entry[nr]
        if not re.match('\s*%', line):
            if not re.search('=', line):
                while not re.search('=', line) and nr < len(bib_entry)-1:
                    val=re.sub('\s*$', '', bib[p_e_type])+" "+re.sub('^\s*', '', re.sub('\t', ' ', line))
                    val=re.sub('%.*', '', val)
                    bib[p_e_type]=remove_quotes(re.sub('\\r$', '', val))
                    nr+=1
                    line=bib_entry[nr]
            else:
                v_break=False
                for e_type in types:
                    if re.match('\s*'+e_type+'\s*=', line, re.I):
                        # TODO: this is not working when title is two lines!
                        line=re.sub('%.*', '', line)
                        bib[e_type]=remove_quotes(re.sub('\\r$', '', re.sub('\t', ' ', line)))
                        p_e_type=e_type
                        nr+=1
                        v_break=True
                        break
                if not v_break:
                    nr+=1
    return bib

pattern=vim.eval("a:pattern")

if pattern == "":
    pat=""
else:
    pat=pattern
pattern=re.compile(pat, re.I)
pattern_b=re.compile('\s*@\w+\s*{.+', re.I)

bibresults={}
for file in files:
    file_ob=open(file, 'r')
    file_l=file_ob.read().split("\n")
    file_ob.close()
    file_len=len(file_l)
    lnr=0
    bibresults[file]={}
    while lnr < file_len:
        lnr+=1
        line=file_l[lnr-1]
	if re.search('@string', line):
            continue
        line_without_ligatures=remove_ligatures(line)
        if re.search(pattern, line_without_ligatures):
            """find first line"""
            b_lnr=lnr
            b_line=line
            while not re.match(pattern_b, b_line) and b_lnr >= 1:
                b_lnr-=1
                b_line=file_l[b_lnr-1]
            """find last line"""
            e_lnr=lnr
            e_line=line
            if re.match(pattern_b, e_line):
                lnr+=1
                e_lnr=lnr
                line=file_l[lnr-1]
                e_line=file_l[lnr-1]
            while not re.match(pattern_b, e_line) and e_lnr <= file_len:
                e_lnr+=1
                e_line=file_l[min(e_lnr-1, file_len-1)]
            e_lnr-=1
            e_line=file_l[min(e_lnr-1, file_len-1)]
            while re.match('\s*$', e_line):
                e_lnr-=1
                e_line=file_l[e_lnr-1]
            bib_entry=file_l[b_lnr-1:e_lnr]
            if bib_entry != [] and not re.search('@string', bib_entry[0]):
                entry_dict=parse_bibentry(bib_entry)
                bibresults[file][b_lnr]=entry_dict
            if lnr < e_lnr:
                lnr=e_lnr
            else:
                lnr+=1
vim.command("let bibresults="+str(bibresults))
END
return bibresults
endfunction
"}}}
" {{{ atplib#bibsearch#SearchBibItems
" the argument should be b:atp_MainFile but in any case it is made in this way.
" it specifies in which file to search for include files.
function! atplib#bibsearch#SearchBibItems()
    let time=reltime()

    let atp_MainFile	= atplib#FullPath(b:atp_MainFile)
    " we are going to make a dictionary { citekey : label } (see :h \bibitem) 
    let l:citekey_label_dict={}

    " make a list of include files.
    let l:includefile_list=[]
    if !exists("b:ListOfFiles") || !exists("b:TypeDict")
	call TreeOfFiles(b:atp_MainFile)
    endif
    let i=1
    for f in b:ListOfFiles
	let type = get(b:TypeDict, f, 'no_type')
	if type == 'no_type' && i
	    call TreeOfFiles(b:atp_MainFile)
	    let i=0
	endif
	if b:TypeDict[f] == "input"
	    call add(l:includefile_list, f)
	endif
    endfor
    call add(l:includefile_list, atp_MainFile) 

    if has("python")
python << PEND
import vim, re
files=vim.eval("l:includefile_list")
citekey_label_dict={}
for f in files:
    f_o=open(f, 'r')
    f_l=f_o.read().split("\n")
    f_o.close()
    for line in f_l:
        if re.match('[^%]*\\\\bibitem', line):
            match=re.search('\\\\bibitem\s*(?:\[([^\]]*)\])?\s*{([^}]*)}\s*(.*)', line)
            if match:
                label=match.group(1)
                if label == None:
                    label = ""
                key=match.group(2)
                if key == None:
                    key = ""
                rest=match.group(3)
                if rest == None:
                    rest = ""
                if key != "":
                    citekey_label_dict[key]={ 'label' : label, 'rest' : rest }
vim.command("let l:citekey_label_dict="+str(citekey_label_dict))
PEND
    else
        " search for bibitems in all include files.
        for l:ifile in l:includefile_list

            let l:input_file = atplib#ReadInputFile(l:ifile,0)

                " search for bibitems and make a dictionary of labels and citekeys
                for l:line in l:input_file
                    if l:line =~# '^[^%]*\\bibitem'
                        let l:label=matchstr(l:line,'\\bibitem\s*\[\zs[^]]*\ze\]')
                        let l:key=matchstr(l:line,'\\bibitem\s*\%(\[[^]]*\]\)\?\s*{\zs[^}]*\ze}') 
                        let l:rest=matchstr(l:line,'\\bibitem\s*\%(\[[^]]*\]\)\?\s*{[^}]*}\s*\zs')
                        if l:key != ""
                            call extend(l:citekey_label_dict, { l:key : { 'label' : l:label, 'rest' : l:rest } }, 'error') 
                        endif
                    endif
                endfor
        endfor
    endif
	
    let g:time_SearchBibItems=reltimestr(reltime(time))
    return l:citekey_label_dict
endfunction
" }}}
"{{{ atplib#bibsearch#showresults
" FLAGS:
" for currently supported flags see ':h atp_bibflags'
" All - all flags	
" L - last flag
" a - author
" e - editor
" t - title
" b - booktitle
" j - journal
" s - series
" y - year
" n - number
" v - volume
" p - pages
" P - publisher
" N - note
" S - school
" h - howpublished
" o - organization
" i - institution
" R - mrreviewer

function! atplib#bibsearch#showresults(bibresults, flags, pattern, bibdict)
 
    "if nothing was found inform the user and return:
    if len(a:bibresults) == count(a:bibresults, {})
	echo "BibSearch: no bib fields matched."
	if g:atp_debugBS
	    exe "redir! >> ".g:atp_TempDir."/BibSeach.log"
	    silent! echo "==========atplib#bibsearch#showresults================="
	    silent! echo "atplib#bibsearch#showresults return A - no bib fields matched. "
	    redir END
	endif
	return 0
    elseif g:atp_debugBS
	    exe "redir! >> ".g:atp_TempDir."/BibSearch.log"
	    silent! echo "==========atplib#bibsearch#showresults================="
	    silent! echo "atplib#bibsearch#showresults return B - found something. "
	    redir END
    endif

    function! s:showvalue(value)
	return substitute(strpart(a:value,stridx(a:value,"=")+1),'^\s*','','')
    endfunction

    let s:z=1
    let l:ln=1
    let l:listofkeys={}
"--------------SET UP FLAGS--------------------------    
	    let l:allflagon=0
	    let l:flagslist=[]
	    let l:kwflagslist=[]

    " flags o and i are synonims: (but refer to different entry keys): 
	if a:flags =~# 'i' && a:flags !~# 'o'
	    let l:flags=substitute(a:flags,'i','io','') 
	elseif a:flags !~# 'i' && a:flags =~# 'o'
	    let l:flags=substitute(a:flags,'o','oi','')
	endif
	if a:flags !~# 'All'
	    if a:flags =~# 'L'
"  		if strpart(a:flags,0,1) != '+'
"  		    let l:flags=b:atp_LastBibFlags . substitute(a:flags, 'L', '', 'g')
"  		else
 		    let l:flags=b:atp_LastBibFlags . substitute(a:flags, 'L', '', 'g')
"  		endif
		let g:atp_LastBibFlags = deepcopy(b:atp_LastBibFlags)
	    else
		if a:flags == "" 
		    let l:flags=g:defaultbibflags
		elseif strpart(a:flags,0,1) != '+' && a:flags !~ 'All' 
		    let l:flags=a:flags
		elseif strpart(a:flags,0,1) == '+' && a:flags !~ 'All'
		    let l:flags=g:defaultbibflags . strpart(a:flags,1)
		endif
	    endif
	    let b:atp_LastBibFlags=substitute(l:flags,'+\|L','','g')
		if l:flags != ""
		    let l:expr='\C[' . g:bibflagsstring . ']' 
		    while len(l:flags) >=1
			let l:oneflag=strpart(l:flags,0,1)
    " if we get a flag from the variable g:bibflagsstring we copy it to the list l:flagslist 
			if l:oneflag =~ l:expr
			    let l:flagslist=add(l:flagslist, l:oneflag)
			    let l:flags=strpart(l:flags,1)
    " if we get '@' we eat ;) two letters to the list l:kwflagslist			
			elseif l:oneflag == '@'
			    let l:oneflag=strpart(l:flags,0,2)
			    if index(keys(g:kwflagsdict),l:oneflag) != -1
				let l:kwflagslist=add(l:kwflagslist,l:oneflag)
			    endif
			    let l:flags=strpart(l:flags,2)
    " remove flags which are not defined
			elseif l:oneflag !~ l:expr && l:oneflag != '@'
			    let l:flags=strpart(l:flags,1)
			endif
		    endwhile
		endif
	else
    " if the flag 'All' was specified. 	    
	    let l:flagslist=split(g:defaultallbibflags, '\zs')
	    let l:af=substitute(a:flags,'All','','g')
	    for l:kwflag in keys(g:kwflagsdict)
		if a:flags =~ '\C' . l:kwflag	
		    call extend(l:kwflagslist,[l:kwflag])
		endif
	    endfor
	endif

	"NEW: if there are only keyword flags append default flags
	if len(l:kwflagslist) > 0 && len(l:flagslist) == 0 
	    let l:flagslist=split(g:defaultbibflags,'\zs')
	endif

"   Open a new window.
    let l:bufnr=bufnr("___Bibsearch: " . a:pattern . "___"  )
    if l:bufnr != -1
	let l:bdelete=l:bufnr . "bwipeout"
	exe l:bdelete
    endif
    unlet l:bufnr
    let l:openbuffer=" +setl\\ buftype=nofile\\ filetype=bibsearch_atp " . fnameescape("___Bibsearch: " . a:pattern . "___")
    if g:vertical ==1
	let l:openbuffer="keepalt vsplit " . l:openbuffer 
	let l:skip=""
    else
	let l:openbuffer="keepalt split " . l:openbuffer 
	let l:skip="       "
    endif

    let BufNr	= bufnr("%")
    let LineNr	= line(".")
    let ColNr	= col(".")
    silent exe l:openbuffer

"     set the window options
    silent call atplib#setwindow()
" make a dictionary of clear values, which we will fill with found entries. 	    
" the default value is no<keyname>, which after all is matched and not showed
" SPEED UP:
    let l:values={'bibfield_key' : 'nokey'}	
    for l:flag in g:bibflagslist
	let l:values_clear=extend(l:values,{ g:bibflagsdict[l:flag][0] : 'no' . g:bibflagsdict[l:flag][0] })
    endfor

" SPEED UP: 
    let l:kwflag_pattern="\\C"	
    let l:len_kwflgslist=len(l:kwflagslist)
    let l:kwflagslist_rev=reverse(deepcopy(l:kwflagslist))
    for l:lkwflag in l:kwflagslist
	if index(l:kwflagslist_rev,l:lkwflag) == 0 
	    let l:kwflag_pattern.=g:kwflagsdict[l:lkwflag]
	else
	    let l:kwflag_pattern.=g:kwflagsdict[l:lkwflag].'\|'
	endif
    endfor
"     let b:kwflag_pattern=l:kwflag_pattern

    for l:bibfile in keys(a:bibresults)
	if a:bibresults[l:bibfile] != {}
	    call setline(l:ln, "Found in " . l:bibfile )	
	    let l:ln+=1
	endif
	for l:linenr in copy(sort(keys(a:bibresults[l:bibfile]), "atplib#CompareNumbers"))
	    let l:values=deepcopy(l:values_clear)
	    let b:values=l:values
" fill l:values with a:bibrsults	    
	    let l:values["bibfield_key"]=a:bibresults[l:bibfile][l:linenr]["bibfield_key"]
" 	    for l:key in keys(l:values)
" 		if l:key != 'key' && get(a:bibresults[l:bibfile][l:linenr],l:key,"no" . l:key) != "no" . l:key
" 		    let l:values[l:key]=a:bibresults[l:bibfile][l:linenr][l:key]
" 		endif
" SPEED UP:
		call extend(l:values,a:bibresults[l:bibfile][l:linenr],'force')
" 	    endfor
" ----------------------------- SHOW ENTRIES -------------------------
" first we check the keyword flags, @a,@b,... it passes if at least one flag
" is matched
	    let l:check=0
" 	    for l:lkwflag in l:kwflagslist
" 	        let l:kwflagpattern= '\C' . g:kwflagsdict[l:lkwflag]
" 		if l:values['bibfield_key'] =~ l:kwflagpattern
" 		   let l:check=1
" 		endif
" 	    endfor
	    if l:values['bibfield_key'] =~ l:kwflag_pattern
		let l:check=1
	    endif
	    if l:check == 1 || len(l:kwflagslist) == 0
		let l:linenumber=index(a:bibdict[l:bibfile],l:values["bibfield_key"])+1
 		call setline(l:ln,s:z . ". line " . l:linenumber . "  " . l:values["bibfield_key"])
		let l:ln+=1
 		let l:c0=atplib#count(l:values["bibfield_key"],'{')-atplib#count(l:values["bibfield_key"],'(')

	
" this goes over the entry flags:
		for l:lflag in l:flagslist
" we check if the entry was present in bibfile:
		    if l:values[g:bibflagsdict[l:lflag][0]] != "no" . g:bibflagsdict[l:lflag][0]
" 			if l:values[g:bibflagsdict[l:lflag][0]] =~ a:pattern
			    call setline(l:ln, l:skip . g:bibflagsdict[l:lflag][1] . " = " . s:showvalue(l:values[g:bibflagsdict[l:lflag][0]]))
			    let l:ln+=1
" 			else
" 			    call setline(l:ln, l:skip . g:bibflagsdict[l:lflag][1] . " = " . s:showvalue(l:values[g:bibflagsdict[l:lflag][0]]))
" 			    let l:ln+=1
" 			endif
		    endif
		endfor
		let l:lastline=getline(line('$'))
		let l:c1=atplib#count(l:lastline,'{')-atplib#count(l:lastline,'}')
		let l:c2=atplib#count(l:lastline,'(')-atplib#count(l:lastline,')')
		let l:c3=atplib#count(l:lastline,'\"')
		if l:c0 == 1 && l:c1 == -1
		    call setline(line('$'),substitute(l:lastline,'}\s*$','',''))
		    call setline(l:ln,'}')
		    let l:ln+=1
		elseif l:c0 == 1 && l:c1 == 0	
		    call setline(l:ln,'}')
		    let l:ln+=1
		elseif l:c0 == -1 && l:c2 == -1
		    call setline(line('$'),substitute(l:lastline,')\s*$','',''))
		    call setline(l:ln,')')
		    let l:ln+=1
		elseif l:c0 == -1 && l:c1 == 0	
		    call setline(l:ln,')')
		    let l:ln+=1
		endif
		let l:listofkeys[s:z]=l:values["bibfield_key"]
		let s:z+=1
	    endif
	endfor
    endfor
    if g:atp_debugBS
	let g:pattern	= a:pattern
    endif
    if has("python") || g:atp_bibsearch == "python"
        let pattern_tomatch = substitute(a:pattern, '(', '\\(', 'g')
        let pattern_tomatch = substitute(pattern_tomatch, ')', '\\)', 'g')
        let pattern_tomatch = substitute(pattern_tomatch, '|', '\\|', 'g')
    else
        let pattern_tomatch = a:pattern
    endif
    let pattern_tomatch = substitute(pattern_tomatch, '\Co', 'oe\\=', 'g')
    let pattern_tomatch = substitute(pattern_tomatch, '\CO', 'OE\\=', 'g')
    let pattern_tomatch = substitute(pattern_tomatch, '\Ca', 'ae\\=', 'g')
    let pattern_tomatch = substitute(pattern_tomatch, '\CA', 'AE\\=', 'g')
    if g:atp_debugBS
	let g:pm = pattern_tomatch
    endif
    let pattern_tomatch	= join(split(pattern_tomatch, '\zs\\\@!\\\@<!'),  '[''"{\}]\{,3}')
    if g:atp_debugBS
	let g:pattern_tomatch = pattern_tomatch
    endif
    if pattern_tomatch != "" && pattern_tomatch != ".*"
	silent! call matchadd("Search", '\c' . pattern_tomatch)
	let @/=pattern_tomatch
    endif
    " return l:listofkeys which will be available in the bib search buffer
    " as b:ListOfKeys (see the BibSearch function below)
    let b:ListOfBibKeys = l:listofkeys
    let b:BufNr		= BufNr

    " Resize if the window height is too big.
    if line("$") <= winheight(0)
	exe "resize ".line("$")
    endif
    return l:listofkeys
endfunction
"}}}
autoload/atplib/callback.vim	[[[1
484
" Title: 	Vim library for ATP filetype plugin.
" Author:	Marcin Szamotulski
" Email:	mszamot [AT] gmail [DOT] com
" Note:		This file is a part of Automatic Tex Plugin for Vim.
" URL:		https://launchpad.net/automatictexplugin
" Language:	tex


" Compilation Call Back Communication: 
" with some help of D. Munger
" (Communications with compiler script: both in compiler.vim and the python script.)
" atplib#callback#TexReturnCode {{{
function! atplib#callback#TexReturnCode(returncode)
	let b:atp_TexReturnCode=a:returncode
endfunction "}}}
" atplib#callback#BibtexReturnCode {{{
function! atplib#callback#BibtexReturnCode(returncode,...)
	let b:atp_BibtexReturnCode=a:returncode
	let b:atp_BibtexOutput= ( a:0 >= 1 ? a:1 : "" )
endfunction
" }}}
" atplib#callback#MakeidxReturnCode {{{
function! atplib#callback#MakeidxReturnCode(returncode,...)
	let b:atp_MakeidxReturnCode=a:returncode
	let b:atp_MakeidxOutput= ( a:0 >= 1 ? a:1 : "" )
endfunction
" }}}
" atplib#callback#Signs {{{
function! atplib#callback#Signs(bufnr)
    if has("signs")
	if a:bufnr != bufnr("%")
	    if bufwinnr(str2nr(a:bufnr)) != -1
		let cwinnr = bufwinnr(bufnr("%"))
		exe bufwinnr(str2nr(a:bufnr))."wincmd w"
	    else
		return
	    endif
	endif
	sign unplace *
	" This unplaces also signs not in the current buffer

	" This unplaces only signs in the current buffer, but uses 
	" redir => var | signs place buffer=a:bufnr | redir END
	" construct which shows signs on the srceen for a second.
	"
	" There should be a function which lists signs.
	"
" 	let more = &more
" 	let lz	= &lz
" 	set nomore
" 	setl lz
" 	redir => unplace_signs
" 	silent exe "sign place buffer=".a:bufnr
" 	redir END
" 	let &more = more
" 	let &lz = lz
" 	let signs = split(unplace_signs, "\n")
" 	call map(signs, 'matchstr(v:val, ''\<id=\>\zs\d\+\ze'')')
" 	for sign in signs
" 	    exe "sign unplace ".sign." buffer=".a:bufnr
" 	endfor
" 	unlet sign
" 	unlet signs
" 	unlet unplace_signs


	" There is no way of getting list of defined signs in the current buffer.
	" Thus there is no proper way of deleting them. I overwrite them using
	" numbers as names. The vim help tells that there might be at most 120
	" signs.
	
	" But this is not undefineing signs.
	let qflist=getqflist()
	let i=1
	for item in qflist
	    if item['type'] == 'E'
		let hl = 'ErrorMsg'
	    elseif item['type'] == 'W'
		let hl = 'WarningMsg'
	    else
		let hl = 'Normal'
	    endif
	    exe 'sign define '.i.' text='.item['type'].': texthl='.hl
	    if g:atp_ParseLog
		let file = bufname(item['bufnr'])
		if file != "" && bufloaded(file)
		    exe 'sign place '.i.' line='.item['lnum'].' name='.i.' file='.file
		endif
	    else
		exe 'sign place '.i.' line='.item['lnum'].' name='.i.' file='.expand('%:p')
	    endif
	    let i+=1
	endfor
	if exists("cwinnr")
	    exe cwinnr."wincmd w"
	    unlet cwinnr
	endif
    endif
endfunction "}}}
" atplib#callback#CallBack {{{
" a:mode 	= a:verbose 	of s:compiler ( one of 'default', 'silent',
" 				'debug', 'verbose')
" a:commnad	= a:commmand 	of s:compiler 
"		 		( a:commnad = 'AU' if run from background)
"
" Uses b:atp_TexReturnCode which is equal to the value returned by tex
" compiler.
function! atplib#callback#CallBack(bufnr,mode,...)

    " If the compiler was called by autocommand.
    let AU 	= ( a:0 >= 1 ? a:1 : 'COM' )
    " Was compiler called to make bibtex
    let BIBTEX 	= ( a:0 >= 2 ? a:2 : "False" )
    let BIBTEX 	= ( BIBTEX == "True" || BIBTEX == 1 ? 1 : 0 )
    let MAKEIDX	= ( a:0 >= 3 ? a:3 : "False" )
    let MAKEIDX = ( MAKEIDX == "TRUE" || MAKEIDX == 1 ? 1 : 0 )

    if g:atp_debugCallBack
	exe "redir! > ".g:atp_TempDir."/CallBack.log"
    endif

    for cmd in keys(g:CompilerMsg_Dict) 
    if b:atp_TexCompiler =~ '^\s*' . cmd . '\s*$'
	    let Compiler 	= g:CompilerMsg_Dict[cmd]
	    break
	else
	    let Compiler 	= b:atp_TexCompiler
	endif
    endfor
    let b:atp_running	= b:atp_running - 1

    " Read the log file
    cgetfile
    call atplib#compiler#FilterQuickFix()

    " signs
    if g:atp_signs
	call atplib#callback#Signs(a:bufnr)
    endif

    if g:atp_debugCallBack
	silent echo "file=".expand("%:p")
	silent echo "g:atp_HighlightErrors=".g:atp_HighlightErrors
    endif
    if g:atp_HighlightErrors
	call atplib#callback#HighlightErrors()
    endif
    " /this cgetfile is not working (?)/
    let error	= len(getqflist()) + (BIBTEX ? b:atp_BibtexReturnCode : 0)

    " If the log file is open re read it / it has 'autoread' opion set /
    checktime

    " redraw the status line /for the notification to appear as fast as
    " possible/ 
    if a:mode != 'verbose'
	redrawstatus
    endif

    " redraw has values -0,1 
    "  1 do  not redraw 
    "  0 redraw
    "  i.e. redraw at the end of function (this is done to not redraw twice in
    "  this function)
    let l:clist 	= 0
    let atp_DebugMode 	= t:atp_DebugMode

    if b:atp_TexReturnCode == 0 && ( a:mode == 'silent' || atp_DebugMode == 'silent' ) && g:atp_DebugMode_AU_change_cmdheight 
	let &l:cmdheight=g:atp_cmdheight
    endif

    if g:atp_debugCallBack
	let g:debugCB 		= 0
	let g:debugCB_mode 	= a:mode
	let g:debugCB_error 	= error
	silent echo "mode=".a:mode."\nerror=".error
    endif

    let msg_list = []
    let showed_message = 0

    if a:mode == "silent" && !error

	if t:atp_QuickFixOpen 

	    if g:atp_debugCallBack
		let g:debugCB .= 7
	    endif

	    if a:mode =~ "^auto" && t:atp_QuickFixOpen
		cclose
		call add(msg_list, ["[ATP:] no errors, closing quick fix window.", "Normal"])
	    endif
	endif

"     elseif a:mode == "silent" && AU == "COM"
" 	if b:atp_TexReturnCode
" 	    let showed_message		= 1
" 	    call add(msg_list, ["[ATP:] ".Compiler." returned with exit code ".b:atp_TexReturnCode.".", 'ErrorMsg', 'after'])
" 	endif
" 	if BIBTEX && b:atp_BibtexReturnCode
" 	    let showed_message		= 1
" 	    call add(msg_list, ["[ATP:] ".b:atp_BibCompiler." returned with exit code ".b:atp_BibtexReturnCode.".", 'ErrorMsg', 'after'])
" 	endif
" 	if MAKEIDX && b:atp_Makeindex
" 	    let showed_message		= 1
" 	    call add(msg_list, ["[ATP:] makeidx returned with exit code ".b:atp_MakeidxReturnCode.".", 'ErrorMsg', 'after'])
" 	endif
    endif

    if a:mode =~ 'auto' && !error

	if g:atp_debugCallBack
	    let g:debugCB 	.= 3
	endif

	call add(msg_list,["[ATP:] ".b:atp_TexCompiler." returned without errors [b:atp_ErrorFormat=".b:atp_ErrorFormat."]".(g:atp_DefaultDebugMode=='silent'&&atp_DebugMode!='silent'?"\ngoing out of debuging mode.": "."), "Normal", "after"]) 
	let showed_message 	= 1
	let t:atp_DebugMode = g:atp_DefaultDebugMode
	if a:mode =~ "auto" && t:atp_QuickFixOpen
	    cclose
	endif
	let &l:cmdheight 	= g:atp_cmdheight
    endif

    " debug mode with errors
    if a:mode ==? 'debug' && error
	if len(getqflist())

	    if g:atp_debugCallBack
		let g:debugCB .= 4
	    endif

	    let &l:cmdheight 	= g:atp_DebugModeCmdHeight
		let showed_message 	= 1
		if b:atp_ReloadOnError || b:atp_Viewer !~ '^\s*xpdf\>'
		    call add(msg_list, ["[ATP:] ".Compiler." returned with exit code " . b:atp_TexReturnCode . ".", (b:atp_TexReturnCode ? "ErrorMsg" : "Normal"), "before"])
		else
		    call add(msg_list, ["[ATP:] ".Compiler." returned with exit code " . b:atp_TexReturnCode . " output file not reloaded.", (b:atp_TexReturnCode ? "ErrorMsg" : "Normal"), "before"])
		endif
	    if !t:atp_QuickFixOpen
		let l:clist		= 1
	    endif
	endif

	if BIBTEX && b:atp_BibtexReturnCode
	    let l:clist		= 1
	    call add(msg_list, [ "[Bib:] ".b:atp_BibtexCompiler." returned with exit code ".b:atp_BibtexReturnCode .".", "ErrorMsg", "after"])
	    call add(msg_list, [ "BIBTEX_OUTPUT" , "Normal", "after"])
	endif

	if MAKEIDX && b:atp_MakeidxReturnCode
	    let l:clist		= 1
	    call add(msg_list, [ "[Bib:] makeidx returned with exit code ".b:atp_MakeidxReturnCode .".", "ErrorMsg", "after"])
	    call add(msg_list, [ "MAKEIDX_OUTPUT" , "Normal", "after"])
	endif

	" In debug mode, go to first error. 
	if a:mode ==# "Debug"

	    if g:atp_debugCallBack
		let g:debugCB .= 6
	    endif

	    cc
	endif
    endif

    if msg_list == []
	if g:atp_debugCallBack
	    redir END
	endif
	return
    endif

    " Count length of the message:
    let msg_len		= len(msg_list)
    if len(filter(copy(msg_list), "v:val[0] == 'BIBTEX_OUTPUT'")) 
	let msg_len 	+= (BIBTEX ? len(split(b:atp_BibtexOutput, "\\n")) - 1 : - 1 )
    endif
    if len(filter(copy(msg_list), "v:val[0] == 'MAKEIDX_OUTPUT'")) 
	let msg_len 	+= (MAKEIDX ? len(split(b:atp_MakeidxOutput, "\\n")) - 1 : - 1 )
    endif
    " We never show qflist: (that's why it is commented out)
"     let msg_len		+= ((len(getqflist()) <= 7 && !t:atp_QuickFixOpen) ? len(getqflist()) : 0 )

    " Show messages/clist
    
    if g:atp_debugCallBack
	let g:msg_list 	= msg_list
	let g:clist 	= l:clist
	silent echo "msg_list=\n**************\n".join(msg_list, "\n")."\n**************"
	silent echo "l:clist=".l:clist
    endif

    let cmdheight = &l:cmdheight
    if msg_len <= 2
	let add=0
    elseif msg_len <= 7
	let add=1
    else
	let add=2
    endif
    let &l:cmdheight	= max([cmdheight, msg_len+add])
    let g:msg_len=msg_len
    if l:clist && len(getqflist()) > 7 && !t:atp_QuickFixOpen
	let winnr = winnr()
	copen
	exe winnr."wincmd w"
    elseif (a:mode ==? "debug") && !t:atp_QuickFixOpen 
	let l:clist = 1
    endif
    redraw
    let before_msg = filter(copy(msg_list), "v:val[2] == 'before'")
    let after_msg = filter(copy(msg_list), "v:val[2] == 'after'")
    for msg in before_msg 
	exe "echohl " . msg[1]
	echo msg[0]
    endfor
    let l:redraw	= 1
    if l:clist && len(getqflist()) <= 7 && !t:atp_QuickFixOpen
	if g:atp_debugCallBack
	    let g:debugCB .= "clist"
	endif
	try
	    clist
	catch E42:
	endtry
	let l:redraw	= 0
    endif
    for msg in after_msg 
	exe "echohl " . msg[1]
	if msg[0] !=# "BIBTEX_OUTPUT"
	    echo msg[0]
	else
	    echo "       ".substitute(b:atp_BibtexOutput, "\n", "\n       ", "g")
" 	    let bib_output=split(b:atp_BibtexOutput, "\n")
" 	    let len=max([10,len(bib_output)])
" 	    below split +setl\ buftype=nofile\ noswapfile Bibtex\ Output
" 	    setl nospell
" 	    setl nonumber
" 	    setl norelativenumber
" 	    call append(0,bib_output)
" 	    resize 10
" 	    redraw!
" 	    normal gg
" 	    nmap q :bd<CR>
	    let g:debugCB .=" BIBTEX_output "
	endif
    endfor
    echohl None
    if len(msg_list)==0
	redraw
    endif
    let &l:cmdheight = cmdheight
    if g:atp_debugCallBack
	redir END
    endif
endfunction "}}}
"{{{ atplib#callback#LatexPID
"Store LatexPIDs in a variable
function! atplib#callback#LatexPID(pid)
    call add(b:atp_LatexPIDs, a:pid)
    let b:atp_LastLatexPID=a:pid
endfunction "}}}
"{{{ atplib#callback#BibtexPID
"Store BibtexPIDs in a variable
function! atplib#callback#BibtexPID(pid)
    call add(b:atp_BibtexPIDs, a:pid)
endfunction "}}}
"{{{ atplib#callback#MakeindexPID
"Store MakeindexPIDs in a variable
function! atplib#callback#MakeindexPID(pid)
    call add(b:atp_MakeindexPIDs, a:pid)
    let b:atp_LastMakeindexPID =a:pid
endfunction "}}}
"{{{ atplib#callback#PythonPID
"Store PythonPIDs in a variable
function! atplib#callback#PythonPID(pid)
    call add(b:atp_PythonPIDs, a:pid)
endfunction "}}}
"{{{ atplib#callback#MakeindexPID
"Store MakeindexPIDs in a variable
function! atplib#callback#PythonPIDs(pid)
    call add(b:atp_PythonPIDs, a:pid)
    let b:atp_LastPythonPID =a:pid
endfunction "}}}
"{{{ atplib#callback#PIDsRunning
function! atplib#callback#PIDsRunning(var)
" a:var is a string, and might be one of 'b:atp_LatexPIDs', 'b:atp_BibtexPIDs' or
" 'b:atp_MakeindexPIDs'
python << EOL
import psutil, re, sys, vim
var  = vim.eval("a:var")
pids = vim.eval(var)
if len(pids) > 0:
    ps_list=psutil.get_pid_list()
    rmpids=[]
    for lp in pids:
	run=False
	for p in ps_list:
            if str(lp) == str(p):
		run=True
		break
	if not run:
            rmpids.append(lp)
    rmpids.sort()
    rmpids.reverse()
    for pid in rmpids:
	vim.eval("filter("+var+", 'v:val !~ \""+str(pid)+"\"')")
EOL
endfunction "}}}
"{{{ atplib#callback#ProgressBar
function! atplib#callback#ProgressBar(value,pid,bufnr)
    if !exists("g:atp_ProgressBarValues")
	let g:atp_ProgressBarValues = { a:bufnr : {} }
    endif
    if !has_key(g:atp_ProgressBarValues, a:bufnr)
	call extend(g:atp_ProgressBarValues, { a:bufnr, {} })
    endif
    if a:value != 'end'
	let g:atp_ProgressBarValues[a:bufnr][a:pid] = a:value
    else
	call remove(g:atp_ProgressBarValues[a:bufnr], a:pid)
    endif
    if bufwinnr(a:bufnr) != -1
	redrawstatus
    endif
endfunction "}}}
"{{{ atplib#callback#redrawstatus
function! atplib#callback#redrawstatus()
    redrawstatus
endfunction "}}}
"{{{ atplib#callback#CursorMoveI
" function! atplib#callback#CursorMoveI()
"     if mode() != "i"
" 	return
"     endif
"     let cursor_pos=[ line("."), col(".")]
"     call feedkeys("\<left>", "n")
"     call cursor(cursor_pos)
" endfunction "}}}
" {{{ atplib#callback#HighlightErrors
function! atplib#callback#HighlightErrors()
    call atplib#callback#ClearHighlightErrors()
    let qf_list = getqflist()
    for error in qf_list
	if error.type ==? 'e'
	    let hlgroup = g:atp_Highlight_ErrorGroup
	else
	    let hlgroup = g:atp_Highlight_WarningGroup
	endif
	if hlgroup == ""
	    continue
	endif
	let m_id = matchadd(hlgroup, '\%'.error.lnum.'l.*', 20)
	call add(s:matchid, m_id)
	let error_msg=split(error.text, "\n")
    endfor
endfunction "}}}
" {{{ atplib#callback#ClearHighlightErrors
function! atplib#callback#ClearHighlightErrors()
    if !exists("s:matchid")
	let s:matchid=[]
	return
    endif
    for m_id in s:matchid
	try
	    silent call matchdelete(m_id)
	catch /E803:/
	endtry
    endfor
    let s:matchid=[]
endfunction "}}}
"{{{ atplib#callback#Echo
function! atplib#callback#Echo(msg, cmd, hlgroup, ...)
    if a:0 >= 1 && a:1
	redraw
    endif
    exe "echohl ".a:hlgroup
    exe a:cmd." '".a:msg."'"
    echohl None
endfunction "}}}
" vim:fdm=marker:ff=unix:noet:ts=8:sw=4:fdc=1
autoload/atplib/common.vim	[[[1
133
" Author: 	Marcin Szamotulski
" Description: 	This script has functions which have to be called before ATP_files/options.vim 
" Note:		This file is a part of Automatic Tex Plugin for Vim.
" Language:	tex

" This file contains set of functions which are needed to set to set the atp
" options and some common tools.

" Set the project name
"{{{ atplib#common#SetProjectName (function and autocommands)
" This function sets the main project name (b:atp_MainFile)
"
" It is used by EditInputFile which copies the value of this variable to every
" input file included in the main source file. 
"
" nmap gf (GotoFile function) is not using this function.
"
" the b:atp_MainFile variable is set earlier in the startup
" (by the augroup ATP_Syntax_TikzZone), calling SetProjectName to earlier cause
" problems (g:atp_raw_bibinputs undefined). 
"
" ToDo: CHECK IF THIS IS WORKS RECURSIVELY?
" ToDo: THIS FUNCTION SHUOLD NOT SET AUTOCOMMANDS FOR AuTeX function! 
" 	every tex file should be compiled (the compiler function calls the  
" 	right file to compile!
"
" {{{ atplib#common#SetProjectName ( function )
" store a list of all input files associated to some file
function! atplib#common#SetProjectName(...)
    let bang 	= ( a:0 >= 1 ? a:1 : "" )	" do we override b:atp_project	
    let did 	= ( a:0 >= 2 ? a:2 : 1	) 	" do we check if the project name was set
    						" but also overrides the current b:atp_MainFile when 0 	

    " if the project name was already set do not set it for the second time
    " (which sets then b:atp_MainFile to wrong value!)  
    if &filetype == "fd_atp"
	" this is needed for EditInputFile function to come back to the main
	" file.
	let b:atp_MainFile	= ( g:atp_RelativePath ? expand("%:t") : expand("%:p") )
	let s:did_project_name	= 1
    endif

    let g:did_project_name = (exists("s:did_project_name") ? s:did_project_name : -1)
    if exists("s:did_project_name") && s:did_project_name && did && exists("b:atp_MainFile")
	return " project name was already set"
    else
	let s:did_project_name	= 1
    endif

    let b:atp_MainFile	= exists("b:atp_MainFile") && did ? b:atp_MainFile : 
		\ ( g:atp_RelativePath ? expand("%:t") : expand("%:p") )

    if !exists("b:atp_ProjectDir")
	let b:atp_ProjectDir = ( exists("b:atp_ProjectScriptFile") ? fnamemodify(b:atp_ProjectScriptFile, ":h") : fnamemodify(resolve(expand("%:p")), ":h") )
    endif
endfunction
" }}}
"}}}

" This functions sets the value of b:atp_OutDir variable
" {{{ atplib#common#SetOutDir
" This options are set also when editing .cls files.
" It can overwrite the value of b:atp_OutDir
" if arg != 0 then set errorfile option accordingly to b:atp_OutDir
" if a:0 >0 0 then b:atp_atp_OutDir is set iff it doesn't exsits.
function! atplib#common#SetOutDir(arg, ...)

    if exists("b:atp_OutDir") && a:0 >= 1
	return "atp_OutDir EXISTS"
    endif

    " if the user want to be asked for b:atp_OutDir
    if g:askfortheoutdir == 1 
	let b:atp_OutDir=substitute(input("Where to put output? do not escape white spaces "), '\\\s', ' ', 'g')
    endif

    if ( get(getbufvar(bufname("%"),""),"outdir","optionnotset") == "optionnotset" 
		\ && g:askfortheoutdir != 1 
		\ || b:atp_OutDir == "" && g:askfortheoutdir == 1 )
		\ && !exists("$TEXMFOUTPUT")
	 let b:atp_OutDir=( exists("b:atp_ProjectScriptFile") ? fnamemodify(b:atp_ProjectScriptFile, ":h") : fnamemodify(resolve(expand("%:p")), ":h") )

    elseif exists("$TEXMFOUTPUT")
	 let b:atp_OutDir=substitute($TEXMFOUTPUT, '\\\s', ' ', 'g') 
    endif	

    " if arg != 0 then set errorfile option accordingly to b:atp_OutDir
    if bufname("") =~ ".tex$" && a:arg != 0
	 call atplib#common#SetErrorFile()
    endif

    if exists("g:outdir_dict")
	let g:outdir_dict	= extend(g:outdir_dict, {fnamemodify(bufname("%"),":p") : b:atp_OutDir })
    else
	let g:outdir_dict	= { fnamemodify(bufname("%"),":p") : b:atp_OutDir }
    endif
    return b:atp_OutDir
endfunction
" }}}

" This function sets vim 'errorfile' option.
"{{{ atplib#common#SetErrorFile
" let &l:errorfile=b:atp_OutDir . fnameescape(fnamemodify(expand("%"),":t:r")) .".(g:atp_ParseLog ? "_" : "")." "log"
if !exists("g:atp_ParseLog")
    let g:atp_ParseLog = has("python")
endif
function! atplib#common#SetErrorFile()

    " set b:atp_OutDir if it is not set
    if !exists("b:atp_OutDir")
	call atplib#common#SetOutDir(0)
    endif

    " set the b:atp_MainFile varibale if it is not set (the project name)
    if !exists("b:atp_MainFile")
	call atplib#common#SetProjectName()
    endif

    let main_file	= atplib#FullPath(b:atp_MainFile)
    let g:main_file 	= main_file

    " vim doesn't like escaped spaces in file names ( cg, filereadable(),
    " writefile(), readfile() - all acepts a non-escaped white spaces)
    if has("win16") || has("win32") || has("win64") || has("win95")
	let errorfile	= substitute(atplib#append(b:atp_OutDir, '\') . fnamemodify(main_file,":t:r") . ".".(g:atp_ParseLog ? "_" : "")."log", '\\\s', ' ', 'g') 
    else
	let errorfile	= substitute(atplib#append(b:atp_OutDir, '/') . fnamemodify(main_file,":t:r") . ".".(g:atp_ParseLog ? "_" : "")."log", '\\\s', ' ', 'g') 
    endif
    let &l:errorfile	= errorfile
    return &l:errorfile
endfunction
"}}}
" vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1
autoload/atplib/compiler.vim	[[[1
2621
" Author: 	Marcin Szamotulski	
" Note:		this file contain the main compiler function and related tools, to
" 		view the output, see error file.
" Note:		This file is a part of Automatic Tex Plugin for Vim.
" Language:	tex

" Internal Variables
" {{{
" This limits how many consecutive runs there can be maximally.
" Note: compile.py script has hardcoded the same value.
let s:runlimit		= 9
" }}}

" This is the function to view output. It calls compiler if the output is a not
" readable file.
" {{{ atplib#compiler#ViewOutput
" a:1 == "RevSearch" 	if run from RevSearch() function and the output file doesn't
" exsists call compiler and RevSearch().
function! atplib#compiler#ViewOutput(bang,tex_file,xpdf_server,...)

    let tex_file	= atplib#FullPath(a:tex_file)

    let fwd_search	= ( a:bang == "!" ? 1 : 0 )

    call atplib#outdir()

    " Set the correct output extension (if nothing matches set the default '.pdf')
    let ext		= get(g:atp_CompilersDict, matchstr(b:atp_TexCompiler, '^\s*\zs\S\+\ze'), ".pdf") 

    " Read the global options from g:atp_{b:atp_Viewer}Options variables
    let global_options 	= join(map(copy(exists("g:atp_".matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')."Options") ? g:atp_{matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')}Options : []), 'shellescape(v:val)'), " ")
    let local_options 	= join(map(copy(exists("b:atp_".matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')."Options") ? getbufvar(bufnr("%"), "atp_".matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')."Options") : []), 'shellescape(v:val)'), " ")

    " Follow the symbolic link
    let link=resolve(tex_file)
    if link != ""
	let outfile	= fnamemodify(link,":r") . ext
    else
	let outfile	= fnamemodify(tex_file,":r"). ext 
    endif

    if b:atp_Viewer == "xpdf"	
	let viewer	= b:atp_Viewer . " -remote " . shellescape(a:xpdf_server)
    else
	let viewer	= b:atp_Viewer . " "
    endif


    if g:atp_debugV
	let g:global_options = global_options
	let g:local_options  = local_options
	let g:viewer         = viewer
	let g:outfile	     = outfile
    endif
    let view_cmd	= viewer." ".global_options." ".local_options." ".shellescape(outfile)." &"

    if g:atp_debugV
	let g:view_cmd	= view_cmd
    endif

    if filereadable(outfile)
	if b:atp_Viewer == "xpdf"
	    call system(view_cmd)
	else
	    call system(view_cmd)
	    redraw!
	endif
    else
	echomsg "[ATP:] output file do not exists. Calling " . b:atp_TexCompiler
	if fwd_search
	    if g:atp_Compiler == 'python'
		call atplib#compiler#PythonCompiler( 0, 2, 1, 'silent' , "AU" , tex_file, "")
	    else
		call atplib#compiler#Compiler( 0, 2, 1, 'silent' , "AU" , tex_file, "")
	    endif
	else
	    if g:atp_Compiler == 'python'
		call atplib#compiler#PythonCompiler( 0, 1, 1, 'silent' , "AU" , tex_file, "")
	    else
		call atplib#compiler#Compiler( 0, 1, 1, 'silent' , "AU" , tex_file, "")
	    endif
	endif
    endif
    if fwd_search
	let msg = "[SyncTex:] waiting for the viewer "
	let i=1
	let max=20
	while !atplib#compiler#IsRunning(b:atp_Viewer, outfile) && i<=max
	    echo msg
	    sleep 100m
	    redraw
	    let msg.="."
	    let i+=1
	endwhile
	exe "sleep ".g:atp_OpenAndSyncSleepTime
	if i<=max
	    call atplib#compiler#SyncTex("", 0, a:tex_file, a:xpdf_server)
	else
	    echohl WarningMsg
	    echomsg "[SyncTex:] viewer is not running"
	    echohl None
	endif
    endif
endfunction
"}}}
" Forward Search:
" {{{ atplib#compiler#GetSyncData
function! atplib#compiler#GetSyncData(line, col, file)

    let g:file = a:file
     	if !filereadable(fnamemodify(atplib#FullPath(a:file), ":r").'.synctex.gz') 
	    redraw!
	    let cmd=b:atp_TexCompiler." ".join(split(b:atp_TexOptions, ','), " ")." ".shellescape(atplib#FullPath(a:file))
	    if b:atp_TexOptions !~ '\%(-synctex\s*=\s*1\|-src-specials\>\)'
		echomsg "[SyncTex:] b:atp_TexOptions does not contain -synctex=1 or -src-specials switches!"
		return
	    else
		echomsg "[SyncTex:] calling ".get(g:CompilerMsg_Dict, b:atp_TexCompiler, b:atp_TexCompiler)." to generate synctex data. Wait a moment..."
	    endif
 	    call system(cmd) 
 	endif
	" Note: synctex view -i line:col:tex_file -o output_file
	" tex_file must be full path.
	let synctex_cmd="synctex view -i ".a:line.":".a:col.":'".expand("%:p"). "' -o '".fnamemodify(atplib#FullPath(a:file), ":r").".pdf'"

	" SyncTex is fragile for the file name: if it is file name or full path, it
	" must agree literally with what is written in .synctex.gz file
	" first we try with full path then fullpath with /./ included and then with file name without path.
	let synctex_output=split(system(synctex_cmd), "\n")
	if get(synctex_output, 1, '') =~ '^SyncTex Warning: No tag for'
	    " Write better test (above)
	    let cwd = getcwd()
	    exe "lcd ".fnameescape(b:atp_ProjectDir)
	    let path = getcwd()."/./".expand("%:.")
	    exe "lcd ".fnameescape(cwd)
	    let synctex_cmd="synctex view -i ".a:line.":".a:col.":'".path. "' -o '".fnamemodify(atplib#FullPath(a:file), ":r").".pdf'"
	    let synctex_output=split(system(synctex_cmd), "\n")
	    if get(synctex_output, 1, '') =~ '^SyncTex Warning:'
		return [ "no_sync", get(synctex_output, 1, ''), 0 ]
	    endif
	    let synctex_output=split(system(synctex_cmd), "\n")
	    if get(synctex_output, 1, '') =~ '^SyncTex Warning: No tag for'
		let synctex_cmd="synctex view -i ".a:line.":".a:col.":'".a:file. "' -o '".fnamemodify(atplib#FullPath(a:file), ":r").".pdf'"
		let synctex_output=split(system(synctex_cmd), "\n")
		if get(synctex_output, 1, '') =~ '^SyncTex Warning:'
		    return [ "no_sync", get(synctex_output, 1, ''), 0 ]
		endif
	    endif
	endif

	if g:atp_debugSync
	    let g:synctex_cmd=synctex_cmd
	    let g:synctex_output=copy(synctex_output)
	endif

	let page_list=copy(synctex_output)
	call filter(page_list, "v:val =~ '^\\cpage:\\d\\+'")
	let page=get(page_list, 0, "no_sync") 

	let y_coord_list=copy(synctex_output) 
	call filter(y_coord_list, "v:val =~ '^\\cy:\\d\\+'")
	let y_coord=get(y_coord_list, 0, "no sync data")
	let y_coord= ( y_coord != "no sync data" ? matchstr(y_coord, 'y:\zs[0-9.]*') : y_coord )

	let x_coord_list=copy(synctex_output) 
	call filter(x_coord_list, "v:val =~ '^\\cx:\\d\\+'")
	let x_coord=get(x_coord_list, 0, "no sync data")
	let x_coord= ( x_coord != "no sync data" ? matchstr(x_coord, 'x:\zs[0-9.]*') : x_coord )

	if g:atp_debugSync
	    let g:page=page
	    let g:y_coord=y_coord
	    let g:x_coord=x_coord
	endif

	if page == "no_sync"
	    return [ "no_sync", "No SyncTex Data: try on another line (or recompile the document).", 0 ]
	endif
	let page_nr=matchstr(page, '^\cPage:\zs\d\+') 
	let [ b:atp_synctex_pagenr, b:atp_synctex_ycoord, b:atp_synctex_xcoord ] = [ page_nr, y_coord, x_coord ]
	return [ page_nr, y_coord, x_coord ]
endfunction
function! atplib#compiler#SyncShow( page_nr, y_coord)
    if a:y_coord < 300
	let height="top"
    elseif a:y_coord < 500
	let height="middle"
    else
	let height="bottom"
    endif
    if a:page_nr != "no_sync"
	echomsg "[SyncTex:] ".height." of page ".a:page_nr
    else
	echohl WarningMsg
	echomsg "[SyncTex:] ".a:y_coord
" 	echomsg "       You cannot forward search on comment lines, if this is not the case try one or two lines above/below"
	echohl None
    endif
endfunction "}}}
" {{{ atplib#compiler#SyncTex
function! atplib#compiler#SyncTex(bang, mouse, main_file, xpdf_server, ...)
    if g:atp_debugSyncTex
	exe "redir! > ".g:atp_TempDir."/SyncTex.log"
    endif
    let output_check 	= ( a:0 >= 1 && a:1 == 0 ? 0 : 1 )
    let IsRunning_check = ( a:bang == "!" ? 0 : 1 )
    let dryrun 		= ( a:0 >= 2 && a:2 == 1 ? 1 : 0 )
    " Mouse click <S-LeftMouse> is mapped to <LeftMouse>... => thus it first changes
    " the cursor position.
    let [ line, col ] 	= [ line("."), col(".") ]
    let main_file	= atplib#FullPath(a:main_file)
    let ext		= get(g:atp_CompilersDict, matchstr(b:atp_TexCompiler, '^\s*\zs\S\+\ze'), ".pdf")
    let output_file	= fnamemodify(main_file,":r") . ext
    if !filereadable(output_file) && output_check
	" Here should be a test if viewer is running, this can be made with python.
	" this is way viewer starts not well when using :SyncTex command while Viewer
	" is not running.
"        call atplib#compiler#ViewOutput("sync")
"        if g:atp_debugSyncTex
" 	   silent echo "ViewOutput sync"
" 	   redir END
"        endif
       echohl WarningMsg
       echomsg "[SyncTex:] no output file"
       echohl None
       return 2
    endif
    let main_file         = atplib#FullPath(a:main_file)
    let ext		  = get(g:atp_CompilersDict, matchstr(b:atp_TexCompiler, '^\s*\zs\S\+\ze'), ".pdf")
    let link=resolve(main_file)
    if link != ""
        let outfile     = fnamemodify(link,":r") . ext
    else
        let outfile     = fnamemodify(main_file,":r"). ext 
    endif

    if IsRunning_check
	if (!atplib#compiler#IsRunning(b:atp_Viewer, atplib#FullPath(outfile), a:xpdf_server) && output_check) 
	    "Note: I should test here if Xpdf is not holding a file (it might be not
	    "visible through cmdline arguments -> this happens if file is opened in
	    "another server. We can use: xpdf -remote a:xpdf_server "run('echo %f')"
	    echohl WarningMsg
	    echomsg "[SyncTex:] please open the file first. (if file is opend add bang \"!\")"
	    echohl None
	    return
	endif
    endif

    if b:atp_Viewer == "xpdf"
	let [ page_nr, y_coord, x_coord ] = atplib#compiler#GetSyncData(line, col, a:main_file)
	let sync_cmd_page = "xpdf -remote " . shellescape(a:xpdf_server) . " -exec 'gotoPage(".page_nr.")'"
	let sync_cmd_y 	= "xpdf -remote " . shellescape(a:xpdf_server) . " -exec 'scrollDown(".y_coord.")'"
        let sync_cmd_x 	= "xpdf -remote " . shellescape(a:xpdf_server) . " -exec 'scrollRight(".x_coord.")'"
" 	let sync_cmd	= "xpdf -remote " . shellescape(a:xpdf_server) . " -exec 'gotoPage(".page_nr.")'"." -exec 'scrollDown(".y_coord.")'"." -exec 'scrollRight(".x_coord.")'"
	" There is a bug in xpdf. We need to sleep between sending commands:
	let sleep    = ( g:atp_XpdfSleepTime ? 'sleep '.string(g:atp_XpdfSleepTime).'s;' : '' )
	let sync_cmd = "(".sync_cmd_page.";".sleep.sync_cmd_y.")&"
	if !dryrun
	    call system(sync_cmd)
	    call atplib#compiler#SyncShow(page_nr, y_coord)
	endif
    elseif b:atp_Viewer == "okular"
	let [ page_nr, y_coord, x_coord ] = atplib#compiler#GetSyncData(line, col, a:main_file)
	" This will not work in project files. (so where it is mostly needed.) 
	let sync_cmd = "okular --unique ".shellescape(expand("%:p:r")).".pdf\\#src:".line.shellescape(expand("%:p"))." &"
	let sync_args = " ".shellescape(expand("%:p:r")).".pdf\\#src:".line.shellescape(expand("%:p"))." "
	if !dryrun
	    call system(sync_cmd)
	    call atplib#compiler#SyncShow(page_nr, y_coord)
	endif
    elseif b:atp_Viewer =~ '^\s*open'
	let [ page_nr, y_coord, x_coord ] = atplib#compiler#GetSyncData(line, col, a:main_file)
	let sync_cmd = g:atp_DisplaylinePath." ".line." ".shellescape(fnamemodify(atplib#FullPath(b:atp_MainFile), ":r").".pdf")." ".shellescape(expand("%:p"))." &"
	if !dryrun
	    call system(sync_cmd)
	    call atplib#compiler#SyncShow(page_nr, y_coord)
	endif
    elseif b:atp_Viewer == "evince"
	let evince_vim_dbus=split(globpath(&rtp, "ftplugin/ATP_files/evince_vim_dbus.py"), "\n")[0]
	let sync_cmd = g:atp_Python." ".shellescape(evince_vim_dbus)." EVINCE ".shellescape(output_file)." ".line." ".shellescape(main_file)
	call system(sync_cmd)
    elseif b:atp_Viewer =~ '^\s*xdvi\>'
	if exists("g:atp_xdviOptions")
	    let options = " ".join(map(copy(g:atp_xdviOptions), 'shellescape(v:val)'), " ")
	elseif exists("b:atp_xdviOptions")
	    let options = " ".join(map(copy(b:atp_xdviOptions), 'shellescape(v:val)'), " ")
	else
	    let options = " "
	endif

	let sync_cmd = "xdvi ".options.
		\ " -editor '".v:progname." --servername ".v:servername.
		\ " --remote-wait +%l %f' -sourceposition ". 
		\ line.":".col.shellescape(fnameescape(fnamemodify(expand("%"),":p"))). 
		\ " ".fnameescape(output_file)." &"
	let sync_args = " -sourceposition ".line.":".col.shellescape(fnameescape(fnamemodify(expand("%"),":p")))." "
	if !dryrun
	    call system(sync_cmd)
	endif
	if g:atp_debugSyncTex
	    silent echo "sync_cmd=".sync_cmd
	endif
    else
	let sync_cmd=""
	if g:atp_debugSyncTex
	    silent echo "sync_cmd=EMPTY"
	endif
    endif
    if g:atp_debugSyncTex
	let g:sync_cmd = sync_cmd
    endif
   if g:atp_debugSyncTex
       redir END
   endif
    return
endfunction 
"}}}
"
" This function gets the pid of the running compiler
" ToDo: review LatexBox has a better approach!
"{{{ Get PID Functions
function! atplib#compiler#getpid()
	let atplib#compiler#command="ps -ef | grep -v " . $SHELL  . " | grep " . b:atp_TexCompiler . " | grep -v grep | grep " . fnameescape(expand("%")) . " | awk 'BEGIN {ORS=\" \"} {print $2}'" 
	let atplib#compiler#var	= system(atplib#compiler#command)
	return atplib#compiler#var
endfunction
" The same but using python (it is not used)
" TODO: end this.
function! atplib#compiler#PythonGetPID() 
python << EOF
import psutil
latex = vim.eval("b:atp_TexCompiler")
# Make dictionary: xpdf_servername : file
# to test if the server host file use:
# basename(xpdf_server_file_dict().get(server, ['_no_file_'])[0]) == basename(file)
ps_list=psutil.get_pid_list()
latex_running	= False
for pr in ps_list:
	try:
		name=psutil.Process(pr).name
		cmdline=psutil.Process(pr).cmdline
		if name == latex:
			latex_pid=pr
			latex_running=True
			break
	except psutil.error.NoSuchProcess:
		pass
	except psutil.error.AccessDenied:
		pass

if latex_running:
	vim.command("let atplib#compiler#var="+str(latex_pid))
else:
	vim.command("let atplib#compiler#var=''")
EOF
endfunction
function! atplib#compiler#GetPID()
    if g:atp_Compiler == "bash"
	let atplib#compiler#var=atplib#compiler#getpid()
	if atplib#compiler#var != ""
	    echomsg "[ATP:] ".b:atp_TexCompiler . " pid(s): " . atplib#compiler#var 
	else
	    let b:atp_running	= 0
	    echomsg "[ATP:] ".b:atp_TexCompiler . " is not running"
	endif
    else
	call atplib#callback#PIDsRunning("b:atp_LatexPIDs")
	if len(b:atp_LatexPIDs) > 0
	    echomsg "[ATP:] ".b:atp_TexCompiler . " pid(s): " . join(b:atp_LatexPIDs, ", ") 
	else
	    let b:atp_LastLatexPID = 0
	    echomsg "[ATP:] ".b:atp_TexCompiler . " is not running"
	endif
    endif
endfunction
"}}}

" This function compares two files: file written on the disk a:file and the current
" buffer
"{{{ atplib#compiler#compare
" relevant variables:
" g:atp_compare_embedded_comments
" g:atp_compare_double_empty_lines
" Problems:
" This function is too slow it takes 0.35 sec on file with 2500 lines.
	" Ideas:
	" Maybe just compare current line!
	" 		(search for the current line in the written
	" 		file with vimgrep)
function! atplib#compiler#compare(file)
    let l:buffer=getbufline(bufname("%"),"1","$")

    " rewrite l:buffer to remove all comments 
    let l:buffer=filter(l:buffer, 'v:val !~ "^\s*%"')

    let l:i = 0
    if g:atp_compare_double_empty_lines == 0 || g:atp_compare_embedded_comments == 0
    while l:i < len(l:buffer)-1
	let l:rem=0
	" remove comment lines at the end of a line
	if g:atp_compare_embedded_comments == 0
	    let l:buffer[l:i] = substitute(l:buffer[l:i],'%.*$','','')
	endif

	" remove double empty lines (i.e. from two conecutive empty lines
	" the first one is deleted, the second remains), if the line was
	" removed we do not need to add 1 to l:i (this is the role of
	" l:rem).
	if g:atp_compare_double_empty_lines == 0 && l:i< len(l:buffer)-2
	    if l:buffer[l:i] =~ '^\s*$' && l:buffer[l:i+1] =~ '^\s*$'
		call remove(l:buffer,l:i)
		let l:rem=1
	    endif
	endif
	if l:rem == 0
	    let l:i+=1
	endif
    endwhile
    endif
 
    " do the same with a:file
    let l:file=filter(a:file, 'v:val !~ "^\s*%"')

    let l:i = 0
    if g:atp_compare_double_empty_lines == 0 || g:atp_compare_embedded_comments == 0
    while l:i < len(l:file)-1
	let l:rem=0
	" remove comment lines at the end of a line
	if g:atp_compare_embedded_comments == 0
	    let l:file[l:i] = substitute(a:file[l:i],'%.*$','','')
	endif
	
	" remove double empty lines (i.e. from two conecutive empty lines
	" the first one is deleted, the second remains), if the line was
	" removed we do not need to add 1 to l:i (this is the role of
	" l:rem).
	if g:atp_compare_double_empty_lines == 0 && l:i < len(l:file)-2
	    if l:file[l:i] =~ '^\s*$' && l:file[l:i+1] =~ '^\s*$'
		call remove(l:file,l:i)
		let l:rem=1
	    endif
	endif
	if l:rem == 0
	    let l:i+=1
	endif
    endwhile
    endif

"     This is the way to make it not sensitive on new line signs.
"     let file_j		= join(l:file)
"     let buffer_j	= join(l:buffer)
"     return file_j !=# buffer_j

    return l:file !=# l:buffer
endfunction
" function! atplib#compiler#sompare(file) 
"     return Compare(a:file)
" endfunction
" This is very fast (0.002 sec on file with 2500 lines) 
" but the proble is that vimgrep greps the buffer rather than the file! 
" so it will not indicate any differences.
function! atplib#compiler#NewCompare()
    let line 		= getline(".")
    let lineNr		= line(".")
    let saved_loclist 	= getloclist(0)
    try
	exe "lvimgrep /^". escape(line, '\^$') . "$/j " . fnameescape(expand("%:p"))
    catch /E480:/ 
    endtry
"     call setloclist(0, saved_loclist)
    let loclist		= getloclist(0)
    call map(loclist, "v:val['lnum']")
    return !(index(loclist, lineNr)+1)
endfunction

"}}}

" This function copies the file a:input to a:output
"{{{ atplib#compiler#copy
function! atplib#compiler#copy(input,output)
	call writefile(readfile(a:input),a:output)
endfunction
"}}}
"{{{ atplib#compiler#GetSid
function! atplib#compiler#GetSid()
    return matchstr(expand('<sfile>'), '\zs<SNR>\d\+_\ze.*$')
endfunction 
let atplib#compiler#compiler_SID = atplib#compiler#GetSid() "}}}
"{{{ atplib#compiler#SidWrap
function! atplib#compiler#SidWrap(func)
    return atplib#compiler#compiler_SID . a:func
endfunction "}}}
" {{{ atplib#compiler#SetBiberSettings
function! atplib#compiler#SetBiberSettings()
    if b:atp_BibCompiler !~# '^\s*biber\>'
	return
    elseif !exists("atplib#compiler#biber_keep_done")
	let atplib#compiler#biber_keep_done = 1
	if index(g:atp_keep, "run.xml") == -1
	    let g:atp_keep += [ "run.xml" ]
	endif
	if index(g:atp_keep, "bcf") == -1
	    let g:atp_keep += [ "bcf" ]
	endif
    endif
endfunction "}}}
" {{{ atplib#compiler#IsRunning
" This function checks if program a:program is running a file a:file.
" a:file should be full path to the file.
function! atplib#compiler#IsRunning(program, file, ...)
    " Since there is an issue in psutil on OS X, we cannot run this function:
    " http://code.google.com/p/psutil/issues/detail?id=173
    " Reported by F.Heiderich.
    if has("mac") || has("gui_mac")
	let atplib#compiler#running=1
	return atplib#compiler#running
    endif

let s:return_is_running=0
python << EOF
import vim, psutil, os, pwd
from psutil import NoSuchProcess
x=0
program =vim.eval("a:program")
f       =vim.eval("a:file")
pat     ="|".join(vim.eval("a:000"))
for pid in psutil.get_pid_list():
    try:
        p=psutil.Process(pid)
        if p.username == pwd.getpwuid(os.getuid())[0] and re.search(program, p.cmdline[0]):
            for arg in p.cmdline:
                if arg == f or re.search(pat, arg):
                    x=1
                    break
        if x:
            break
    except psutil.error.NoSuchProcess:
        pass
    except psutil.error.AccessDenied:
        pass
    except IndexError:
        pass
vim.command("let s:return_is_running="+str(x))
EOF
let l:return=s:return_is_running
unlet s:return_is_running
return l:return
endfunction
" }}}
"{{{ atplib#compiler#Kill
" This function kills all running latex processes.
" a slightly better approach would be to kill compile.py scripts
" the argument is a list of pids
" a:1 if present supresses a message.
function! atplib#compiler#Kill(bang)
    if !has("python")
	if a:bang != "!"
	    echohl WarningMsg
	    echomsg "[ATP:] you need python suppor" 
	    echohl None
	endif
	return
    endif
    if len(b:atp_LatexPIDs)
	call atplib#KillPIDs(b:atp_LatexPIDs)
    endif
    if len(b:atp_PythonPIDs)
	call atplib#KillPIDs(b:atp_PythonPIDs)
    endif
    if has_key(g:atp_ProgressBarValues, bufnr("%"))
	let g:atp_ProgressBarValues[bufnr("%")]={}
    endif
    let b:atp_running = 0
endfunction
"}}}

" THE MAIN COMPILER FUNCTIONs:
" This function is called to run TeX compiler and friends as many times as necessary.
" Makes references and bibliographies (supports bibtex), indexes.  
"{{{ atplib#compiler#MakeLatex
" Function Arguments:
function! atplib#compiler#MakeLatex(bang, mode, start)

    if a:mode =~# '^s\%[ilent]$'
	let mode = 'silent'
    elseif a:mode =~# '^d\%[ebug]$'
	let mode = 'debug'
    elseif a:mode =~# 'D\%[ebug]$'
	let mode = 'Debug'
    elseif a:mode =~#  '^v\%[erbose]$'
	let mode = 'debug'
    else
	let mode = t:atp_DebugMode
    endif

    " and a:bang are not yet used by makelatex.py
    let PythonMakeLatexPath 	= split(globpath(&rtp, "ftplugin/ATP_files/makelatex.py"), "\n")[0]
    let interaction 	    	= ( mode=="verbose" ? b:atp_VerboseLatexInteractionMode : 'nonstopmode' )
    let tex_options	    	= shellescape(b:atp_TexOptions.',-interaction='.interaction)
    let ext			= get(g:atp_CompilersDict, matchstr(b:atp_TexCompiler, '^\s*\zs\S\+\ze'), ".pdf") 
    let ext			= substitute(ext, '\.', '', '')
    let global_options 		= join((exists("g:atp_".matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')."Options") ? g:atp_{matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')}Options : []), ";")
    let local_options 		= join((exists("b:atp_".matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')."Options") ? getbufvar(bufnr("%"), "atp_".matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')."Options") : []), ";")
    if global_options !=  "" 
	let viewer_options  	= global_options.";".local_options
    else
	let viewer_options  	= local_options
    endif
    let reload_viewer 		= ( index(g:atp_ReloadViewers, b:atp_Viewer)+1  ? ' --reload-viewer ' : '' )
    let reload_on_error 	= ( b:atp_ReloadOnError ? ' --reload-on-error ' : '' )
    let bibliographies 		= join(keys(filter(copy(b:TypeDict), "v:val == 'bib'")), ',')

    let cmd=g:atp_Python." ".PythonMakeLatexPath.
		\ " --texfile ".shellescape(atplib#FullPath(b:atp_MainFile)).
		\ " --bufnr ".bufnr("%").
		\ " --start ".a:start.
		\ " --output-format ".ext.
		\ " --verbose ".mode.
		\ " --cmd ".b:atp_TexCompiler.
		\ " --bibcmd ".b:atp_BibCompiler.
		\ " --bibliographies ".shellescape(bibliographies).
		\ " --outdir ".shellescape(b:atp_OutDir).
		\ " --keep ". shellescape(join(g:atp_keep, ',')).
		\ " --tex-options ".tex_options.
		\ " --servername ".v:servername.
		\ " --viewer ".shellescape(b:atp_Viewer).
		\ " --xpdf-server ".shellescape(b:atp_XpdfServer).
		\ " --viewer-options ".shellescape(viewer_options).
		\ " --progname ".v:progname.
		\ " --logdir ".shellescape(g:atp_TempDir).
		\ (g:atp_callback ? "" : " --no-callback ").
		\ (t:atp_DebugMode=='verbose'||mode=='verbose'?' --env ""': " --env ".shellescape(b:atp_TexCompilerVariable)).
		\ reload_viewer . reload_on_error
    unlockvar g:atp_TexCommand
    let g:atp_TexCommand=cmd
    lockvar g:atp_TexCommand

    " Write file
    call atplib#write("COM", "silent")

    if mode == "verbose"
	exe ":!".cmd
    elseif has("win16") || has("win32") || has("win64")
	let output=system(cmd)
    else
	let output=system(cmd." &")
    endif
endfunction

"}}}
" {{{ atplib#compiler#PythonCompiler
function! atplib#compiler#PythonCompiler(bibtex, start, runs, verbose, command, filename, bang, ...)
    " a:1	= b:atp_XpdfServer (default value)

    if fnamemodify(&l:errorfile, ":p") != fnamemodify(a:filename, ":p:r").".".(g:atp_ParseLog ? "_" : "")."log"
	exe "setl errorfile=".fnamemodify(a:filename, ":p:r").".".(g:atp_ParseLog ? "_" : "")."log"
    endif

    " Kill comiple.py scripts if there are too many of them.
    if len(b:atp_PythonPIDs) >= b:atp_MaxProcesses && b:atp_MaxProcesses
	let a=copy(b:atp_LatexPIDs)
	try
	    if b:atp_KillYoungest
		" Remove the newest PIDs (the last in the b:atp_PythonPIDs)
		let pids=remove(b:atp_LatexPIDs, b:atp_MaxProcesses, -1) 
	    else
		" Remove the oldest PIDs (the first in the b:atp_PythonPIDs) /works nicely/
		let pids=remove(b:atp_LatexPIDs, 0, max([len(b:atp_PythonPIDs)-b:atp_MaxProcesses-1,0]))
	    endif
	    call atplib#KillPIDs(pids)
	catch E684:
	endtry
    endif

    " Set biber setting on the fly
    call atplib#compiler#SetBiberSettings()

    if !has('gui') && a:verbose == 'verbose' && len(b:atp_LatexPIDs) > 0
	redraw!
	echomsg "[ATP:] please wait until compilation stops."
	return

	" This is not working: (I should kill compile.py scripts)
	echomsg "[ATP:] killing all instances of ".get(g:CompilerMsg_Dict,b:atp_TexCompiler,'TeX')
	call atplib#KillPIDs(b:atp_LatexPIDs,1)
	sleep 1
	PID
    endif

    " Debug varibles
    " On Unix the output of compile.py run by this function is available at
    " g:atp_TempDir/compiler.py.log
    if g:atp_debugPythonCompiler
	call atplib#Log("PythonCompiler.log", "", "init")
	call atplib#Log("PythonCompiler.log", "a:bibtex=".a:bibtex)
	call atplib#Log("PythonCompiler.log", "a:start=".a:start)
	call atplib#Log("PythonCompiler.log", "a:runs=".a:runs)
	call atplib#Log("PythonCompiler.log", "a:verbose=".a:verbose)
	call atplib#Log("PythonCompiler.log", "a:command=".a:command)
	call atplib#Log("PythonCompiler.log", "a:filename=".a:filename)
	call atplib#Log("PythonCompiler.log", "a:bang=".a:bang)
    endif

    if !exists("t:atp_DebugMode")
	let t:atp_DebugMode = g:atp_DefaultDebugMode
    endif

    if t:atp_DebugMode !~ 'verbose$' && a:verbose !~ 'verbose$'
	let b:atp_LastLatexPID = -1
    endif
    
    if t:atp_DebugMode !~ "silent$" && b:atp_TexCompiler !~ "luatex" &&
		\ (b:atp_TexCompiler =~ "^\s*\%(pdf\|xetex\)" && b:atp_Viewer == "xdvi" ? 1 :  
		\ b:atp_TexCompiler !~ "^\s*pdf" && b:atp_TexCompiler !~ "xetex" &&  (b:atp_Viewer == "xpdf" || b:atp_Viewer == "epdfview" || b:atp_Viewer == "acroread" || b:atp_Viewer == "kpdf"))
	 
	echohl WaningMsg | echomsg "[ATP:] your ".b:atp_TexCompiler." and ".b:atp_Viewer." are not compatible:" 
	echomsg "       b:atp_TexCompiler=" . b:atp_TexCompiler	
	echomsg "       b:atp_Viewer=" . b:atp_Viewer	
	echohl None
    endif
    if !has('clientserver')
	if has("win16") || has("win32") || has("win64") || has("win95")
	    echohl WarningMsg
	    echomsg "[ATP:] ATP needs +clientserver vim compilation option."
	    echohl None
	else
	    echohl WarningMsg
	    echomsg "[ATP:] python compiler needs +clientserver vim compilation option."
	    echomsg "       falling back to g:atp_Compiler=\"bash\""
	    echohl None
	    let g:atp_Compiler = "bash"
	    return
	endif
    endif


    " Set options for compile.py
    let interaction 		= ( a:verbose=="verbose" ? b:atp_VerboseLatexInteractionMode : 'nonstopmode' )
    let tex_options		= b:atp_TexOptions.',-interaction='.interaction
    let ext			= get(g:atp_CompilersDict, matchstr(b:atp_TexCompiler, '^\s*\zs\S\+\ze'), ".pdf") 
    let ext			= substitute(ext, '\.', '', '')

    let viewer			= matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')
    let global_options 		= join((exists("g:atp_".viewer."Options") ? {"g:atp_".viewer."Options"} : []), ";") 
    let local_options 		= join((exists("b:atp_".viewer."Options") ? {"b:atp_".viewer."Options"} : []), ";")
    if global_options !=  "" 
	let viewer_options  	= global_options.";".local_options
    else
	let viewer_options  	= local_options
    endif
    let bang 			= ( a:bang == '!' ? ' --bang ' : '' ) 
    let bibtex 			= ( a:bibtex ? ' --bibtex ' : '' )
    let reload_on_error 	= ( b:atp_ReloadOnError ? ' --reload-on-error ' : '' )
    let gui_running 		= ( has("gui_running") ? ' --gui-running ' : '' )
    let reload_viewer 		= ( index(g:atp_ReloadViewers, b:atp_Viewer)+1  ? ' --reload-viewer ' : '' )
    let aucommand 		= ( a:command == "AU" ? ' --aucommand ' : '' )
    let no_progress_bar 	= ( g:atp_ProgressBar ? '' : ' --no-progress-bar ' )
    let bibliographies 		= join(keys(filter(copy(b:TypeDict), "v:val == 'bib'")), ',')
    let autex_wait		= ( b:atp_autex_wait ? ' --autex_wait ' : '') 
    let xpdf_server		= ( a:0 >= 1 ? a:1 : b:atp_XpdfServer )

    " Set the command
    let cmd=g:atp_Python." ".g:atp_PythonCompilerPath." --command ".b:atp_TexCompiler
		\ ." --tex-options ".shellescape(tex_options)
		\ ." --tempdir ".shellescape(b:atp_TempDir)
		\ ." --verbose ".a:verbose
		\ ." --file ".shellescape(atplib#FullPath(a:filename))
		\ ." --bufnr ".bufnr("%")
		\ ." --output-format ".ext
		\ ." --runs ".a:runs
		\ ." --servername ".v:servername
		\ ." --start ".a:start 
		\ ." --viewer ".shellescape(b:atp_Viewer)
		\ ." --xpdf-server ".shellescape(xpdf_server)
		\ ." --viewer-options ".shellescape(viewer_options) 
		\ ." --keep ". shellescape(join(g:atp_keep, ','))
		\ ." --progname ".v:progname
		\ ." --bibcommand ".b:atp_BibCompiler
		\ ." --bibliographies ".shellescape(bibliographies)
		\ ." --logdir ".shellescape(g:atp_TempDir)
		\ .(g:atp_callback ? "" : " --no-callback ")
		\ ." --progressbar_file " . shellescape(g:atp_ProgressBarFile)
		\ .(t:atp_DebugMode=~'verbose$'||a:verbose=~'verbose$'?' --env ""': " --env ".shellescape(b:atp_TexCompilerVariable))
		\ . bang . bibtex . reload_viewer . reload_on_error . gui_running . aucommand . no_progress_bar
		\ . autex_wait

    " Write file
    if g:atp_debugPythonCompiler
	call atplib#Log("PythonCompiler.log", "PRE WRITING b:atp_changedtick=".b:atp_changedtick." b:changedtick=".b:changedtick)
    endif
    call atplib#write(a:command,"silent")

    if g:atp_debugPythonCompiler
	call atplib#Log("PythonCompiler.log", "POST WRITING b:atp_changedtick=".b:atp_changedtick." b:changedtick=".b:changedtick)
    endif
    unlockvar g:atp_TexCommand
    let g:atp_TexCommand	= cmd
    lockvar g:atp_TexCommand

    " Call compile.py
    let b:atp_running += ( a:verbose != "verbose" ?  1 : 0 )
    if a:verbose == "verbose"
	exe ":!".cmd
    elseif g:atp_debugPythonCompiler && has("unix") 
	call system(cmd." 2".g:atp_TempDir."/PythonCompiler.log &")
    elseif has("win16") || has("win32") || has("win64")
	call system(cmd)
    else
	call system(cmd." &")
    endif
    if g:atp_debugPythonCompiler
	call atplib#Log("PythonCompiler.log", "END b:atp_changedtick=".b:atp_changedtick." b:changedtick=".b:changedtick)
    endif
endfunction
" }}}
" {{{ atplib#compiler#LocalCompiler
function! atplib#compiler#LocalCompiler(mode, ...)
    let debug_mode = ( a:0 && a:1 != ""  ? a:1 : 'silent' )

    let subfiles = atplib#search#SearchPackage('subfiles')
    let file = expand("%:p")
    let tmpdir = b:atp_TempDir . matchstr(tempname(), '\/\w\+\/\d\+')
    let extensions = [ 'aux', 'bbl' ]
    let main_file = atplib#FullPath(b:atp_MainFile)
    if a:mode == "n" && subfiles
	" if subfiles package is used.
	" compilation is done in the current directory.
python << ENDPYTHON
import vim, os, os.path, shutil, re

file = vim.eval("file")
basename = os.path.splitext(file)[0]
mainfile_base = os.path.splitext(vim.eval("main_file"))[0]
# read the local aux file (if present) find all new \newlabel{} commands
# if they are present in the original aux file substitute them (this part is
# not working) if not add them at the end. Note that after running pdflatex
# the local aux file becomes agian short.
if os.path.exists(basename+".aux"):
    local_aux_file = open(basename+".aux", "r")
    local_aux = local_aux_file.readlines()
    local_aux_file.close()
    if os.path.exists(mainfile_base+".aux"):
        main_aux_file  = open(mainfile_base+".aux", "r")
        main_aux = main_aux_file.readlines()
        main_aux_file.close()
    else:
        main_aux = []
# There is no sens of comparing main_aux and local_aux!
    pattern = re.compile('^\\\\newlabel.*$', re.M)
    local_labels = re.findall(pattern, "".join(local_aux))
    def get_labels(line):
        return re.match('\\\\newlabel\s*{([^}]*)}', line).group(1)
    local_labels_names = map(get_labels, local_labels)
    local_labels_dict = dict(zip(local_labels_names, local_labels))
    values = {}
    for label in local_labels_names:
        match = re.search('^\\\\newlabel\s*{'+re.escape(label)+'}.*', "\n".join(main_aux), re.M)
        if not match:
            main_aux.append(local_labels_dict[label]+"\n")
#     elif match.group(0) != local_labels_dict[label]:
#         print("A "+match.group(0))
#         print("A "+local_labels_dict[label])
#         print("\n".join(main_aux))
#         main_aux.remove(match.group(0))
#         main_aux.append(local_labels_dict[label])
    main_aux_file  = open(mainfile_base+".aux", "w")
    main_aux_file.write("".join(main_aux))
    main_aux_file.close()

# copy the main aux file to local directory
extensions = vim.eval("extensions")
for ext in extensions:
    if os.path.exists(mainfile_base+"."+ext):
        try:
            shutil.copy(mainfile_base+"."+ext, basename+"."+ext)
        except shutil.Error:
            pass
ENDPYTHON
	if g:atp_Compiler == 'python'
	    call  atplib#compiler#PythonCompiler(0,0,1,debug_mode,'COM',expand("%:p"),"",b:atp_LocalXpdfServer)
	else
	    call atplib#compiler#Compiler(0,0,1,debug_mode, 'COM', expand(":p"), "", b:atp_LocalXpdfServer)
	endif
    endif
endfunction
" }}}
" {{{ atplib#compiler#Compiler 
" This is the MAIN FUNCTION which sets the command and calls it.
" NOTE: the <filename> argument is not escaped!
" a:verbose	= silent/verbose/debug
" 	debug 	-- switch to show errors after compilation.
" 	verbose -- show compiling procedure.
" 	silent 	-- compile silently (gives status information if fails)
" a:start	= 0/1/2
" 		1 start viewer
" 		2 start viewer and make reverse search
"
function! atplib#compiler#Compiler(bibtex, start, runs, verbose, command, filename, bang, ...)
	" a:1	= b:atp_XpdfServer (default value)
	let XpdfServer = ( a:0 >= 1 ? a:1 : b:atp_XpdfServer )
	if fnamemodify(&l:errorfile, ":p") != fnamemodify(a:filename, ":p:r").".".(g:atp_ParseLog ? "_" : "")."log"
	    exe "setl errorfile=".fnamemodify(a:filename, ":p:r").".".(g:atp_ParseLog ? "_" : "")."log"
	endif
    
	" Set biber setting on the fly
	call atplib#compiler#SetBiberSettings()

	if !has('gui') && a:verbose == 'verbose' && b:atp_running > 0
	    redraw!
	    echomsg "[ATP:] please wait until compilation stops."
	    return
	endif

	if g:atp_debugCompiler
	    exe "redir! > ".g:atp_TempDir."/Compiler.log"
	    silent echomsg "________ATP_COMPILER_LOG_________"
	    silent echomsg "changedtick=" . b:changedtick . " atp_changedtick=" . b:atp_changedtick
	    silent echomsg "a:bibtex=" . a:bibtex . " a:start=" . a:start . " a:runs=" . a:runs . " a:verbose=" . a:verbose . " a:command=" . a:command . " a:filename=" . a:filename . " a:bang=" . a:bang
	    silent echomsg "1 b:changedtick=" . b:changedtick . " b:atp_changedtick" . b:atp_changedtick . " b:atp_running=" .  b:atp_running
	endif

	if has('clientserver') && !empty(v:servername) && g:atp_callback && a:verbose != 'verbose'
	    let b:atp_running+=1
	endif
	call atplib#outdir()
    	" IF b:atp_TexCompiler is not compatible with the viewer
	" ToDo: (move this in a better place). (luatex can produce both pdf and dvi
	" files according to options so this is not the right approach.) 
	if !exists("t:atp_DebugMode")
	    let t:atp_DebugMode = g:atp_DefaultDebugMode
	endif
	if t:atp_DebugMode !=? "silent" && b:atp_TexCompiler !~? "luatex" &&
		    \ (b:atp_TexCompiler =~ "^\s*\%(pdf\|xetex\)" && b:atp_Viewer == "xdvi" ? 1 :  
		    \ b:atp_TexCompiler !~ "^\s*pdf" && b:atp_TexCompiler !~ "xetex" &&  (b:atp_Viewer == "xpdf" || b:atp_Viewer == "epdfview" || b:atp_Viewer == "acroread" || b:atp_Viewer == "kpdf"))
	     
	    echohl WaningMsg | echomsg "[ATP:] your ".b:atp_TexCompiler." and ".b:atp_Viewer." are not compatible:" 
	    echomsg "       b:atp_TexCompiler=" . b:atp_TexCompiler	
	    echomsg "       b:atp_Viewer=" . b:atp_Viewer	
	    echohl None
	endif

	" There is no need to run more than ~5 (s:runlimit=9) consecutive runs
	" this prevents from running tex as many times as the current line
	" what can be done by a mistake using the range for the command.
	if ( a:runs > s:runlimit )
	    let runs = s:runlimit
	else
	    let runs = a:runs
	endif

	let tmpdir=b:atp_TempDir . matchstr(tempname(), '\/\w\+\/\d\+')
	let tmpfile=atplib#append(tmpdir, "/") . fnamemodify(a:filename,":t:r")
	if g:atp_debugCompiler
	    let g:tmpdir=tmpdir
	    let g:tmpfile=tmpfile
	endif
	call system("mkdir -m 0700 -p ".shellescape(tmpdir))
" 	if exists("*mkdir")
" 	    call mkdir(tmpdir, "p", 0700)
" 	else
" 	    echoerr "[ATP:] Your vim doesn't have mkdir function, please try the python compiler."
" 	    return
" 	endif

	" SET THE NAME OF OUTPUT FILES
	" first set the extension pdf/dvi
	let ext	= get(g:atp_CompilersDict, matchstr(b:atp_TexCompiler, '^\s*\zs\S\+\ze'), ".pdf") 

	" check if the file is a symbolic link, if it is then use the target
	" name.
	let link=system("readlink " . a:filename)
	if link != ""
	    let basename=fnamemodify(link,":r")
	else
	    let basename=a:filename
	endif

	" finally, set the output file names. 
	let outfile 	= b:atp_OutDir . fnamemodify(basename,":t:r") . ext
	let outaux  	= b:atp_OutDir . fnamemodify(basename,":t:r") . ".aux"
	let outbbl  	= b:atp_OutDir . fnamemodify(basename,":t:r") . ".bbl"
	let tmpaux  	= fnamemodify(tmpfile, ":r") . ".aux"
	let tmpbbl  	= fnamemodify(tmpfile, ":r") . ".bbl"
	let tmptex  	= fnamemodify(tmpfile, ":r") . ".tex"
	let outlog  	= b:atp_OutDir . fnamemodify(basename,":t:r") . ".log"
	let syncgzfile 	= b:atp_OutDir . fnamemodify(basename,":t:r") . ".synctex.gz"
	let syncfile 	= b:atp_OutDir . fnamemodify(basename,":t:r") . ".synctex"

"	COPY IMPORTANT FILES TO TEMP DIRECTORY WITH CORRECT NAME 
"	except log and aux files.
	let list	= copy(g:atp_keep)
	call filter(list, 'v:val != "log"')
	for i in list
	    let ftc	= b:atp_OutDir . fnamemodify(basename,":t:r") . "." . i
	    if filereadable(ftc)
		call atplib#compiler#copy(ftc,tmpfile . "." . i)
	    endif
	endfor

" 	HANDLE XPDF RELOAD 
	let reload_viewer = ( index(g:atp_ReloadViewers, b:atp_Viewer) == '-1' ? ' --reload-viewer ' : '' )
	if b:atp_Viewer =~ '^\s*xpdf\>' && reload_viewer
	    if a:start
		"if xpdf is not running and we want to run it.
		let Reload_Viewer = b:atp_Viewer . " -remote " . shellescape(XpdfServer) . " " . shellescape(outfile) . " ; "
	    else
" TIME: this take 1/3 of time! 0.039
		call atplib#compiler#xpdfpid()
		" I could use here atplib#compiler#XpdPid(), the reason to not use it is that
		" then there is a way to run ATP without python.
		if atplib#compiler#xpdfpid != ""
		    "if xpdf is running (then we want to reload it).
		    "This is where I use 'ps' command to check if xpdf is
		    "running.
		    let Reload_Viewer = b:atp_Viewer . " -remote " . shellescape(XpdfServer) . " -reload ; "
		else
		    "if xpdf is not running (but we do not want
		    "to run it).
		    let Reload_Viewer = " "
		endif
	    endif
	else
	    if a:start
		" if b:atp_Viewer is not running and we want to open it.
		" the name of this variable is not missleading ...
		let Reload_Viewer = b:atp_Viewer . " " . shellescape(outfile) . " ; "
		" If run through RevSearch command use source specials rather than
		" just reload:
		if str2nr(a:start) == 2
		    let synctex		= atplib#compiler#SidWrap('SyncTex')
		    let callback_rs_cmd = v:progname . " --servername " . v:servername . " --remote-expr " . "'".synctex."()' ; "
		    let Reload_Viewer	= callback_rs_cmd
		endif
	    else
		" If b:atp_Viewer is not running then we do not want to
		" open it.
		let Reload_Viewer = " "
	    endif	
	endif
	if g:atp_debugCompiler
	    let g:Reload_Viewer = Reload_Viewer
	endif

" 	IF OPENING NON EXISTING OUTPUT FILE
"	only xpdf needs to be run before (we are going to reload it)
	if a:start && b:atp_Viewer == "xpdf"
	    let xpdf_options	= ( exists("g:atp_xpdfOptions")  ? join(map(copy(g:atp_xpdfOptions), 'shellescape(v:val)'), " ") : "" )." ".(exists("b:xpdfOptions") ? join(map(copy(getbufvar(0, "atp_xpdfOptions")), 'shellescape(v:val)'), " ") : " ")
	    let start 	= b:atp_Viewer . " -remote " . shellescape(XpdfServer) . " " . xpdf_options . " & "
	else
	    let start = ""	
	endif

"	SET THE COMMAND 
	let interaction = ( a:verbose=="verbose" ? b:atp_VerboseLatexInteractionMode : 'nonstopmode' )
	let variable	= ( a:verbose!="verbose" ? substitute(b:atp_TexCompilerVariable, ';', ' ', 'g') : '' ) 
	let comp	= variable . " " . b:atp_TexCompiler . " " . substitute(b:atp_TexOptions, ',', ' ','g') . " -interaction=" . interaction . " -output-directory=" . shellescape(tmpdir) . " " . shellescape(a:filename)
	let vcomp	= variable . " " . b:atp_TexCompiler . " " . substitute(b:atp_TexOptions, ',', ' ','g')  . " -interaction=". interaction . " -output-directory=" . shellescape(tmpdir) .  " " . shellescape(a:filename)
	
	" make function:
" 	let make	= "vim --servername " . v:servername . " --remote-expr 'MakeLatex\(\"".tmptex."\",1,0\)'"

	if a:verbose == 'verbose' 
	    let texcomp=vcomp
	else
	    let texcomp=comp
	endif
	if runs >= 2 && a:bibtex != 1
	    " how many times we want to call b:atp_TexCompiler
	    let i=1
	    while i < runs - 1
		let i+=1
		let texcomp=texcomp . " ; " . comp
	    endwhile
	    if a:verbose != 'verbose'
		let texcomp=texcomp . " ; " . comp
	    else
		let texcomp=texcomp . " ; " . vcomp
	    endif
	endif
	
	if a:bibtex == 1
	    " this should be decided using the log file as well.
	    if filereadable(outaux)
" 		call atplib#compiler#copy(outaux,tmpfile . ".aux")
		let texcomp="bibtex " . shellescape(fnamemodify(outaux, ":t")) . "; ".g:atp_cpcmd." ".shellescape(outbbl)." ".shellescape(tmpbbl).";" . comp . "  1>/dev/null 2>&1 "
	    else
		let texcomp=comp.";clear;".g:atp_cpcmd." ".shellescape(tmpaux)." ".shellescape(outaux)."; bibtex ".shellescape(fnamemodify(outaux, ":t")).";".g:atp_cpcmd." ".shellescape(outbbl)." ".shellescape(tmpbbl)."; ".comp." 1>/dev/null 2>&1 "
	    endif
	    if a:verbose != 'verbose'
		let texcomp=texcomp . " ; " . comp
	    else
		let texcomp=texcomp . " ; " . vcomp
	    endif
	endif

	" catch the status
	if has('clientserver') && v:servername != "" && g:atp_callback == 1

	    let catchstatus_cmd = v:progname . ' --servername ' . v:servername . ' --remote-expr ' . 
			\ shellescape('atplib#callback#TexReturnCode')  . '\($?\) ; ' 
	else
	    let catchstatus_cmd = ''
	endif

	" copy output file (.pdf\|.ps\|.dvi)
" 	let cpoptions	= "--remove-destination"
	let cpoptions	= ""
	let cpoutfile	= g:atp_cpcmd." ".cpoptions." ".shellescape(atplib#append(tmpdir,"/"))."*".ext." ".shellescape(atplib#append(b:atp_OutDir,"/"))." ; "

	if a:start
	    let command	= "(" . texcomp . " ; (" . catchstatus_cmd . " " . cpoutfile . " " . Reload_Viewer . " ) || ( ". catchstatus_cmd . " " . cpoutfile . ") ; " 
	else
	    " 	Reload on Error:
	    " 	for xpdf it copies the out file but does not reload the xpdf
	    " 	server for other viewers it simply doesn't copy the out file.
	    if b:atp_ReloadOnError || a:bang == "!"
		if a:bang == "!"
		    let command="( ".texcomp." ; ".catchstatus_cmd." ".g:atp_cpcmd." ".cpoptions." ".shellescape(tmpaux)." ".shellescape(b:atp_OutDir)." ; ".cpoutfile." ".Reload_Viewer 
		else
		    let command="( (".texcomp." && ".g:atp_cpcmd." ".cpoptions." ".shellescape(tmpaux)." ".shellescape(b:atp_OutDir)." ) ; ".catchstatus_cmd." ".cpoutfile." ".Reload_Viewer 
		endif
	    else
		if b:atp_Viewer =~ '\<xpdf\>'
		    let command="( ".texcomp." && (".catchstatus_cmd.cpoutfile." ".Reload_Viewer." ".g:atp_cpcmd." ".cpoptions." ".shellescape(tmpaux)." ".shellescape(b:atp_OutDir)." ) || (".catchstatus_cmd." ".cpoutfile.") ; " 
		else
		    let command="(".texcomp." && (".catchstatus_cmd.cpoutfile." ".Reload_Viewer." ".g:atp_cpcmd." ".cpoptions." ".shellescape(tmpaux)." ".shellescape(b:atp_OutDir)." ) || (".catchstatus_cmd.") ; " 
		endif
	    endif
	endif

    if g:atp_debugCompiler
	silent echomsg "Reload_Viewer=" . Reload_Viewer
	let g:Reload_Viewer 	= Reload_Viewer
	let g:command		= command
    elseif g:atp_debugCompiler >= 2 
	silent echomsg "command=" . command
    endif

	" Preserve files with extension belonging to the g:atp_keep list variable.
	let copy_cmd=""
	let j=1
	for i in g:atp_keep 
" ToDo: this can be done using internal vim functions.
	    if i != "aux"
		let copycmd=g:atp_cpcmd." ".cpoptions." ".shellescape(atplib#append(tmpdir,"/")).
			    \ "*.".i." ".shellescape(atplib#append(b:atp_OutDir,"/")) 
	    else
		let copycmd=g:atp_cpcmd." ".cpoptions." ".shellescape(atplib#append(tmpdir,"/")).
			    \ "*.".i." ".shellescape(atplib#append(b:atp_OutDir,"/".fnamemodify(b:atp_MainFile, ":t:r")."_aux")) 
	    endif

	    if j == 1
		let copy_cmd=copycmd
	    else
		let copy_cmd=copy_cmd . " ; " . copycmd	  
	    endif
	    let j+=1
	endfor
	if g:atp_debugCompiler
	    let g:copy_cmd = copy_cmd
	endif
	let command=command . " " . copy_cmd . " ; " 

	" Callback:
	if has('clientserver') && v:servername != "" && g:atp_callback == 1

" 	    let callback	= atplib#compiler#SidWrap('CallBack')
	    let callback_cmd 	= v:progname . ' --servername ' . v:servername . ' --remote-expr ' . 
				    \ shellescape('atplib#callback#CallBack').'\(\"'.bufnr("%").'\",\"'.a:verbose.'\",\"'.a:command.'\",\"'.a:bibtex.'\"\)'. " ; "

	    let command = command . " " . callback_cmd

	    if g:atp_debugCompiler
		silent echomsg "callback_cmd=" . callback_cmd
	    endif
	endif


 	let rmtmp="rm -rf " . shellescape(fnamemodify(tmpdir, ":h")) . "; "
	let command=command . " " . rmtmp . ") &"

	if str2nr(a:start) != 0 
	    let command=start . command
	endif

	" Take care about backup and writebackup options.
	if g:atp_debugCompiler
	    silent echomsg "BEFORE WRITING: b:changedtick=" . b:changedtick . " b:atp_changedtick=" . b:atp_changedtick . " b:atp_running=" .  b:atp_running
	endif

	call atplib#write(a:command, "silent")

	if g:atp_debugCompiler
	    silent echomsg "AFTER WRITING: b:changedtick=" . b:changedtick . " b:atp_changedtick=" . b:atp_changedtick . " b:atp_running=" .  b:atp_running
	endif

	if a:verbose != 'verbose'
" "cd ".shellescape(tmpdir).";".
	    let g:atp_TexOutput=system(command)
	else
	    let command="!clear;" . texcomp . " " . cpoutfile . " " . copy_cmd
	    exe command
	endif

	unlockvar g:atp_TexCommand
	let g:atp_TexCommand=command
	lockvar g:atp_TexCommand

    if g:atp_debugCompiler
	silent echomsg "command=" . command
	redir END
    endif
endfunction
"}}}
"{{{ aptlib#compiler#ThreadedCompiler
function! atplib#compiler#ThreadedCompiler(bibtex, start, runs, verbose, command, filename, bang)

    " Write file:
    if g:atp_debugPythonCompiler
	call atplib#Log("ThreadedCompiler.log", "", "init")
	call atplib#Log("ThreadedCompiler.log", "PRE WRITING b:atp_changedtick=".b:atp_changedtick." b:changedtick=".b:changedtick)
    endif

    call atplib#write(a:command, "silent")

    if g:atp_debugPythonCompiler
	call atplib#Log("ThreadedCompiler.log", "POST WRITING b:atp_changedtick=".b:atp_changedtick." b:changedtick=".b:changedtick)
    endif

    " Kill comiple.py scripts if there are too many of them.
    if len(b:atp_PythonPIDs) >= b:atp_MaxProcesses && b:atp_MaxProcesses
	let a=copy(b:atp_LatexPIDs)
	try
	    if b:atp_KillYoungest
		" Remove the newest PIDs (the last in the b:atp_PythonPIDs)
		let pids=remove(b:atp_LatexPIDs, b:atp_MaxProcesses, -1) 
	    else
		" Remove the oldest PIDs (the first in the b:atp_PythonPIDs) /works nicely/
		let pids=remove(b:atp_LatexPIDs, 0, max([len(b:atp_PythonPIDs)-b:atp_MaxProcesses-1,0]))
	    endif
	    echomsg string(a)." ".string(pids)." ".string(b:atp_LatexPIDs)
	    call atplib#KillPIDs(pids)
	catch E684:
	endtry
	echomsg string(b:atp_LatexPIDs)
    endif

    " Set biber setting on the fly
    call atplib#compiler#SetBiberSettings()

    if !has('gui') && a:verbose == 'verbose' && len(b:atp_LatexPIDs) > 0
	redraw!
	echomsg "[ATP:] please wait until compilation stops."
	return

	" This is not working: (I should kill compile.py scripts)
	echomsg "[ATP:] killing all instances of ".get(g:CompilerMsg_Dict,b:atp_TexCompiler,'TeX')
	call atplib#KillPIDs(b:atp_LatexPIDs,1)
	sleep 1
	PID
    endif

    " Debug varibles
    " On Unix the output of compile.py run by this function is available at
    " g:atp_TempDir/compiler.py.log
    if g:atp_debugPythonCompiler
	call atplib#Log("ThreadedCompiler.log", "", "init")
	call atplib#Log("ThreadedCompiler.log", "a:bibtex=".a:bibtex)
	call atplib#Log("ThreadedCompiler.log", "a:start=".a:start)
	call atplib#Log("ThreadedCompiler.log", "a:runs=".a:runs)
	call atplib#Log("ThreadedCompiler.log", "a:verbose=".a:verbose)
	call atplib#Log("ThreadedCompiler.log", "a:command=".a:command)
	call atplib#Log("ThreadedCompiler.log", "a:filename=".a:filename)
	call atplib#Log("ThreadedCompiler.log", "a:bang=".a:bang)
    endif

    if !exists("t:atp_DebugMode")
	let t:atp_DebugMode = g:atp_DefaultDebugMode
    endif

    if t:atp_DebugMode != 'verbose' && a:verbose != 'verbose'
	let b:atp_LastLatexPID = -1
    endif
    
    if t:atp_DebugMode != "silent" && b:atp_TexCompiler !~ "luatex" &&
		\ (b:atp_TexCompiler =~ "^\s*\%(pdf\|xetex\)" && b:atp_Viewer == "xdvi" ? 1 :  
		\ b:atp_TexCompiler !~ "^\s*pdf" && b:atp_TexCompiler !~ "xetex" &&  (b:atp_Viewer == "xpdf" || b:atp_Viewer == "epdfview" || b:atp_Viewer == "acroread" || b:atp_Viewer == "kpdf"))
	 
	echohl WaningMsg | echomsg "[ATP:] your ".b:atp_TexCompiler." and ".b:atp_Viewer." are not compatible:" 
	echomsg "       b:atp_TexCompiler=" . b:atp_TexCompiler	
	echomsg "       b:atp_Viewer=" . b:atp_Viewer	
	echohl None
    endif
    if !has('clientserver')
	if has("win16") || has("win32") || has("win64") || has("win95")
	    echohl WarningMsg
	    echomsg "[ATP:] ATP needs +clientserver vim compilation option."
	    echohl None
	else
	    echohl WarningMsg
	    echomsg "[ATP:] python compiler needs +clientserver vim compilation option."
	    echomsg "       falling back to g:atp_Compiler=\"bash\""
	    echohl None
	    let g:atp_Compiler = "bash"
	    return
	endif
    endif


    " Set options for compile.py
    let interaction 		= ( a:verbose=="verbose" ? b:atp_VerboseLatexInteractionMode : 'nonstopmode' )
    let tex_options		= b:atp_TexOptions.',-interaction='.interaction
"     let g:tex_options=tex_options
    let ext			= get(g:atp_CompilersDict, matchstr(b:atp_TexCompiler, '^\s*\zs\S\+\ze'), ".pdf") 
    let ext			= substitute(ext, '\.', '', '')

    let global_options 		= join((exists("g:atp_".matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')."Options") ? g:atp_{matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')}Options : []), ";") 
    let local_options 		= join(( exists("atp_".matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')."Options") ? getbufvar(bufnr("%"), "atp_".matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')."Options") : []), ";")
    if global_options !=  "" 
	let viewer_options  	= global_options.";".local_options
    else
	let viewer_options  	= local_options
    endif
    let file                    = atplib#FullPath(a:filename)
    let bang 			= ( a:bang == '!' ? ' --bang ' : '' ) 
    let bibtex 			= ( a:bibtex ? ' --bibtex ' : '' )
    let reload_on_error 	= ( b:atp_ReloadOnError ? ' --reload-on-error ' : '' )
    let gui_running 		= ( has("gui_running") ? ' --gui-running ' : '' )
    let reload_viewer 		= ( index(g:atp_ReloadViewers, b:atp_Viewer)+1  ? ' --reload-viewer ' : '' )
    let aucommand 		= ( a:command == "AU" ? ' --aucommand ' : '' )
    let no_progress_bar 	= ( g:atp_ProgressBar ? '' : ' --no-progress-bar ' )
    let bibliographies 		= join(keys(filter(copy(b:TypeDict), "v:val == 'bib'")), ',')
    let autex_wait		= ( b:atp_autex_wait ? ' --autex_wait ' : '') 
    let keep                    = join(g:atp_keep, ',')

python << ENDPYTHON
import vim, threading
import sys, errno, os.path, shutil, subprocess, psutil, re, tempfile, optparse, glob
import traceback, atexit

from os import chdir, mkdir, putenv, devnull
from collections import deque

####################################
#
#       Functions:   
#
####################################

def nonempty(string):
    if str(string) == '':
        return False
    else:
        return True

def decode_list(byte):
    return byte.decode()

def latex_progress_bar(cmd):
# Run latex and send data for progress bar,

    child = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    # If I remove the code below and only put child.wait() 
    # then vim crashes.
    pid   = child.pid
    vim.eval("atplib#callback#LatexPID("+str(pid)+")")
    debug_file.write("latex pid "+str(pid)+"\n")
    stack = deque([])
    while True:
        try:
            out = child.stdout.read(1).decode()
        except UnicodeDecodeError:
            debug_file.write("UNICODE DECODE ERROR:\n")
            debug_file.write(child.stdout.read(1))
            debug_file.write("\n")
            debug_file.write("stack="+''.join(stack)+"\n")
            out = ""
        if out == '' and child.poll() != None:
            break
        if out != '':
            stack.append(out)

            if len(stack)>10:
                stack.popleft()
            match = re.match('\[(\n?\d(\n|\d)*)({|\])',str(''.join(stack)))
            if match:
                vim.eval("atplib#callback#ProgressBar("+match.group(1)[match.start():match.end()]+","+str(pid)+")")
    child.wait()
    vim.eval("atplib#callback#ProgressBar('end',"+str(pid)+")")
    vim.eval("atplib#callback#PIDsRunning(\"b:atp_LatexPIDs\")")
    return child

def xpdf_server_file_dict():
# Make dictionary of the type { xpdf_servername : [ file, xpdf_pid ] },

# to test if the server host file use:
# basename(xpdf_server_file_dict().get(server, ['_no_file_'])[0]) == basename(file)
# this dictionary always contains the full path (Linux).
# TODO: this is not working as I want to:
#    when the xpdf was opened first without a file it is not visible in the command line
#    I can use 'xpdf -remote <server> -exec "run('echo %f')"'
#    where get_filename is a simple program which returns the filename. 
#    Then if the file matches I can just reload, if not I can use:
#          xpdf -remote <server> -exec "openFile(file)"
    ps_list=psutil.get_pid_list()
    server_file_dict={}
    for pr in ps_list:
        try:
            name=psutil.Process(pr).name
            cmdline=psutil.Process(pr).cmdline
            if name == 'xpdf':
                try:
                    ind=cmdline.index('-remote')
                except:
                    ind=0
                if ind != 0 and len(cmdline) >= 1:
                    server_file_dict[cmdline[ind+1]]=[cmdline[len(cmdline)-1], pr]
        except psutil.error.NoSuchProcess:
            pass
        except psutil.error.AccessDenied:
            pass
    return server_file_dict


####################################
#
#       Options:   
#
####################################
tex_file        = vim.eval("b:atp_MainFile")
command         = vim.eval("b:atp_TexCompiler")
bibcommand      = vim.eval("b:atp_BibCompiler")
progname        = vim.eval("v:progname")
if vim.eval("aucommand") == ' --aucommand ':
    aucommand_bool  = True
    aucommand="AU"
else:
    aucommand_bool  = False
    aucommand="COM"
command_opt     = list(filter(nonempty,re.split('\s*,\s*', vim.eval("tex_options"))))
mainfile_fp     = vim.eval("file")
output_format   = vim.eval("ext")
if output_format == "pdf":
    extension = ".pdf"
else:
    extension = ".dvi"
runs            = int(vim.eval("a:runs"))
servername      = vim.eval("v:servername")
start           = str(vim.eval("a:start"))
viewer          = vim.eval("b:atp_Viewer")
if vim.eval("autex_wait") == "--autex_wait":
    autex_wait      = True
else:
    autex_wait      = False
XpdfServer      = vim.eval("b:atp_XpdfServer")
viewer_rawopt   = re.split('\s*;\s*', vim.eval("viewer_options"))
viewer_it       = list(filter(nonempty, viewer_rawopt))
viewer_opt      =[]
for opt in viewer_it:
    viewer_opt.append(opt)
viewer_rawopt   = viewer_opt
if viewer == "xpdf" and XpdfServer != None:
    viewer_opt.extend(["-remote", XpdfServer])
verbose         = vim.eval("a:verbose")
keep            = vim.eval("keep").split(',')
keep            = list(filter(nonempty, keep))

def keep_filter_aux(string):
    if string == 'aux':
        return False
    else:
        return True

def keep_filter_log(string):
    if string == 'log':
        return False
    else:
        return True

def mysplit(string):
        return re.split('\s*=\s*', string)

env             = list(map(mysplit, list(filter(nonempty, re.split('\s*;\s*',vim.eval("b:atp_TexCompilerVariable"))))))

# Boolean options
if vim.eval("reload_viewer") == ' --reload-viewer ':
    reload_viewer   = True
else:
    reload_viewer   = False
if vim.eval("bibtex") == ' --bibtex ':
    bibtex          = True
else:
    bibtex          = False
bibliographies  = vim.eval("bibliographies").split(",")
bibliographies  = list(filter(nonempty, bibliographies))
if vim.eval("a:bang") == "!":
    bang            = True
else:
    bang            = False
if vim.eval("reload_on_error") == ' --reload-on-error ':
    reload_on_error = True
else:
    reload_on_error = False
if vim.eval("gui_running") == ' --gui-running ':
    gui_running     = True
else:
    gui_running     = False
if vim.eval("no_progress_bar") == ' --no-progress-bar ':
    progress_bar    = False
else:
    progress_bar    = True

# Debug file should be changed for sth platform independent
# There should be a switch to get debug info.
logdir          = vim.eval("g:atp_TempDir")
script_logfile  = os.path.join(logdir, 'compile.log')
debug_file      = open(script_logfile, 'w')

debug_file.write("COMMAND "+command+"\n")
debug_file.write("BIBCOMMAND "+bibcommand+"\n")
debug_file.write("BIBCOMMAND "+bibcommand+"\n")
debug_file.write("AUCOMMAND "+aucommand+"\n")
debug_file.write("PROGNAME "+progname+"\n")
debug_file.write("COMMAND_OPT "+str(command_opt)+"\n")
debug_file.write("MAINFILE_FP "+str(mainfile_fp)+"\n")
debug_file.write("OUTPUT FORMAT "+str(output_format)+"\n")
debug_file.write("EXT "+extension+"\n")
debug_file.write("RUNS "+str(runs)+"\n")
debug_file.write("VIM_SERVERNAME "+str(servername)+"\n")
debug_file.write("START "+str(start)+"\n")
debug_file.write("VIEWER "+str(viewer)+"\n")
debug_file.write("XPDF_SERVER "+str(XpdfServer)+"\n")
debug_file.write("VIEWER_OPT "+str(viewer_opt)+"\n")
debug_file.write("DEBUG MODE (verbose) "+str(verbose)+"\n")
debug_file.write("KEEP "+str(keep)+"\n")
debug_file.write("BIBLIOGRAPHIES "+str(bibliographies)+"\n")
# debug_file.write("ENV OPTION "+str(options.env)+"\n")
debug_file.write("ENV "+str(env)+"\n")
debug_file.write("*BIBTEX "+str(bibtex)+"\n")
debug_file.write("*BANG "+str(bang)+"\n")
debug_file.write("*RELOAD_VIEWER "+str(reload_viewer)+"\n")
debug_file.write("*RELOAD_ON_ERROR "+str(reload_on_error)+"\n")
debug_file.write("*GUI_RUNNING "+str(gui_running)+"\n")
debug_file.write("*PROGRESS_BAR "+str(progress_bar)+"\n")

class LatexThread( threading.Thread ):
    def run( self ):
# Author: Marcin Szamotulski <mszamot[@]gmail[.]com>
# This file is a part of Automatic TeX Plugin for Vim.



# readlink is not available on Windows.
        readlink=True
        try:
            from os import readlink
        except ImportError:
            readlink=False

# Cleanup on exit:
        def cleanup(debug_file):
            debug_file.close()
            shutil.rmtree(tmpdir)
#         atexit.register(cleanup, debug_file)

####################################
#
#       Arguments:   
#
####################################
        global tex_file, command, bibcommand, progname, aucommand_bool, aucommand
        global command_opt, mainfile_fp, output_format, extension, runs, servername, start
        global viewer, autex_wait, XpdfServer, viewer_rawopt, viewer_it, viewer_opt
        global viewer_rawopt, verbose, keep, env
        global reload_viewer, bibtex, bibliographies, bang, reload_on_error, gui_running, progress_bar

# If mainfile_fp is not a full path make it. 
#     glob=glob.glob(os.path.join(os.getcwd(),mainfile_fp))
#     if len(glob) != 0:
#         mainfile_fp = glob[0]
        mainfile        = os.path.basename(mainfile_fp)
        mainfile_dir    = os.path.dirname(mainfile_fp)
        if mainfile_dir == "":
            mainfile_fp = os.path.join(os.getcwd(), mainfile)
            mainfile    = os.path.basename(mainfile_fp)
            mainfile_dir= os.path.dirname(mainfile_fp)
        if os.path.islink(mainfile_fp):
            if readlink:
                mainfile_fp = os.readlink(mainfile_fp)
            # The above line works if the symlink was created with full path. 
            mainfile    = os.path.basename(mainfile_fp)
            mainfile_dir= os.path.dirname(mainfile_fp)

        mainfile_dir    = os.path.normcase(mainfile_dir)
        [basename, ext] = os.path.splitext(mainfile)
        output_fp       = os.path.splitext(mainfile_fp)[0]+extension

        try:
            # Send pid to ATP:
            if verbose != "verbose":
                vim.eval("atplib#callback#PythonPID("+str(os.getpid())+")")
####################################
#
#       Make temporary directory,
#       Copy files and Set Environment:
#
####################################
            cwd     = os.getcwd()
            if not os.path.exists(os.path.join(mainfile_dir,".tmp")):
                    # This is the main tmp dir (./.tmp) 
                    # it will not be deleted by this script
                    # as another instance might be using it.
                    # it is removed by Vim on exit.
                os.mkdir(os.path.join(mainfile_dir,".tmp"))
            tmpdir  = tempfile.mkdtemp(dir=os.path.join(mainfile_dir,".tmp"),prefix="")
            debug_file.write("TMPDIR: "+tmpdir+"\n")
            tmpaux  = os.path.join(tmpdir,basename+".aux")

            command_opt.append('-output-directory='+tmpdir)
            latex_cmd      = [command]+command_opt+[mainfile_fp]
            debug_file.write("COMMAND "+str(latex_cmd)+"\n")
            debug_file.write("COMMAND "+" ".join(latex_cmd)+"\n")

# Copy important files to output directory:
# /except the log file/
            os.chdir(mainfile_dir)
            for ext in filter(keep_filter_log,keep):
                file_cp=basename+"."+ext
                if os.path.exists(file_cp):
                    shutil.copy(file_cp, tmpdir)

            tempdir_list = os.listdir(tmpdir)
            debug_file.write("\nls tmpdir "+str(tempdir_list)+"\n")

# Set environment
            for var in env:
                debug_file.write("ENV "+var[0]+"="+var[1]+"\n")
                os.putenv(var[0], var[1])

# Link local bibliographies:
            for bib in bibliographies:
                if os.path.exists(os.path.join(mainfile_dir,os.path.basename(bib))):
                    os.symlink(os.path.join(mainfile_dir,os.path.basename(bib)),os.path.join(tmpdir,os.path.basename(bib)))

####################################
#
#       Compile:   
#
####################################
# Start Xpdf (this can be done before compelation, because we can load file
# into afterwards) in this way Xpdf starts faster (it is already running when
# file compiles). 
# TODO: this might cause problems when the tex file is very simple and short.
# Can we test if xpdf started properly?  okular doesn't behave nicely even with
# --unique switch.

# Latex might not run this might happedn with bibtex (?)
            latex_returncode=0
            if bibtex and os.path.exists(tmpaux):
                if bibcommand == 'biber':
                    bibfname = basename
                else:
                    bibfname = basename+".aux"
                debug_file.write("\nBIBTEX1"+str([bibcommand, bibfname])+"\n")
                os.chdir(tmpdir)
                bibtex_popen=subprocess.Popen([bibcommand, bibfname], stdout=subprocess.PIPE)
                vim.eval("atplib#callback#BibtexPID('"+str(bibtex_popen.pid)+"')")
                vim.eval("atplib#callback#redrawstatus()")
                bibtex_popen.wait()
                vim.eval("atplib#callback#PIDsRunning(\"b:atp_BibtexPIDs\")")
                os.chdir(mainfile_dir)
                bibtex_returncode=bibtex_popen.returncode
                bibtex_output=re.sub('"', '\\"', bibtex_popen.stdout.read())
                debug_file.write("BIBTEX RET CODE "+str(bibtex_returncode)+"\nBIBTEX OUTPUT\n"+bibtex_output+"\n")
                if verbose != 'verbose':
                    vim.eval("atplib#callback#BibtexReturnCode('"+str(bibtex_returncode)+"',\""+str(bibtex_output)+"\")")
                else:
                    print(bibtex_output)
                # We need run latex at least 2 times
                bibtex=False
                runs=max([runs, 2])
# If bibtex contained errros we stop:
#     if not bibtex_returncode:
#         runs=max([runs, 2])
#     else:
#         runs=1
            elif bibtex:
                # we need run latex at least 3 times
                runs=max([runs, 3])

            debug_file.write("\nRANGE="+str(range(1,runs+1))+"\n")
            debug_file.write("RUNS="+str(runs)+"\n")
            for i in range(1, runs+1):
                debug_file.write("RUN="+str(i)+"\n")
                debug_file.write("DIR="+str(os.getcwd())+"\n")
                tempdir_list = os.listdir(tmpdir)
                debug_file.write("ls tmpdir "+str(tempdir_list)+"\n")
                debug_file.write("BIBTEX="+str(bibtex)+"\n")

                if verbose == 'verbose' and i == runs:
#       <SIS>compiler() contains here ( and not bibtex )
                    debug_file.write("VERBOSE"+"\n")
                    latex=subprocess.Popen(latex_cmd)
                    pid=latex.pid
                    debug_file.write("latex pid "+str(pid)+"\n")
                    latex.wait()
                    latex_returncode=latex.returncode
                    debug_file.write("latex ret code "+str(latex_returncode)+"\n")
                else:
                    if progress_bar and verbose != 'verbose':
                        latex=latex_progress_bar(latex_cmd)
                    else:
                        latex = subprocess.Popen(latex_cmd, stdout=subprocess.PIPE)
                        pid   = latex.pid
                        vim.eval("atplib#callback#LatexPID("+str(pid)+")")
                        debug_file.write("latex pid "+str(pid)+"\n")
                        latex.wait()
                        vim.eval("atplib#callback#PIDsRunning(\"b:atp_LatexPIDs\")")
                    latex_returncode=latex.returncode
                    debug_file.write("latex return code "+str(latex_returncode)+"\n")
                    tempdir_list = os.listdir(tmpdir)
                    debug_file.write("JUST AFTER LATEX ls tmpdir "+str(tempdir_list)+"\n")
                # Return code of compilation:
                if verbose != "verbose":
                    vim.eval("atplib#callback#TexReturnCode('"+str(latex_returncode)+"')")
                if bibtex and i == 1:
                    if bibcommand == 'biber':
                        bibfname = basename
                    else:
                        bibfname = basename+".aux"
                    debug_file.write("BIBTEX2 "+str([bibcommand, bibfname])+"\n")
                    debug_file.write(os.getcwd()+"\n")
                    tempdir_list = os.listdir(tmpdir)
                    debug_file.write("ls tmpdir "+str(tempdir_list)+"\n")
                    os.chdir(tmpdir)
                    bibtex_popen=subprocess.Popen([bibcommand, bibfname], stdout=subprocess.PIPE)
                    vim.eval("atplib#callback#BibtexPID('"+str(bibtex_popen.pid)+"')")
                    vim.eval("atplib#callback#redrawstatus()")
                    bibtex_popen.wait()
                    vim.eval("atplib#callback#PIDsRunning(\"b:atp_BibtexPIDs\")")
                    os.chdir(mainfile_dir)
                    bibtex_returncode=bibtex_popen.returncode
                    bibtex_output=re.sub('"', '\\"', bibtex_popen.stdout.read())
                    debug_file.write("BIBTEX2 RET CODE"+str(bibtex_returncode)+"\n")
                    if verbose != 'verbose':
                        vim.eval("atplib#callback#BibtexReturnCode('"+str(bibtex_returncode)+"',\""+str(bibtex_output)+"\")")
                    else:
                        print(bibtex_output)
# If bibtex had errors we stop, 
# at this point tex file was compiled at least once.
#         if bibtex_returncode:
#             debug_file.write("BIBTEX BREAKE "+str(bibtex_returncode)+"\n")
#             break

####################################
#
#       Copy Files:
#
####################################

# Copy files:
            os.chdir(tmpdir)
            for ext in list(filter(keep_filter_aux,keep))+[output_format]:
                file_cp=basename+"."+ext
                if os.path.exists(file_cp):
                    debug_file.write(file_cp+' ')
                    shutil.copy(file_cp, mainfile_dir)

# Copy aux file if there were no compilation errors or if it doesn't exists in mainfile_dir.
# copy aux file to _aux file (for atplib#tools#GrepAuxFile)
            if latex_returncode == 0 or not os.path.exists(os.path.join(mainfile_dir, basename+".aux")):
                file_cp=basename+".aux"
                if os.path.exists(file_cp):
                    shutil.copy(file_cp, mainfile_dir)
            file_cp=basename+".aux"
            if os.path.exists(file_cp):
                shutil.copy(file_cp, os.path.join(mainfile_dir, basename+"._aux"))
            os.chdir(cwd)

####################################
#
#       Call Back Communication:   
#
####################################
            if verbose != "verbose":
                debug_file.write("CALL BACK "+"atplib#callback#CallBack('"+str(verbose)+"','"+aucommand+"','"+str(bibtex)+"')"+"\n")
                vim.eval("atplib#callback#CallBack('"+str(verbose)+"','"+aucommand+"','"+str(bibtex)+"')")
                # return code of compelation is returned before (after each compilation).


####################################
#
#       Reload/Start Viewer:   
#
####################################
            if re.search(viewer, '^\s*xpdf\e') and reload_viewer:
                # The condition tests if the server XpdfServer is running
                xpdf_server_dict=xpdf_server_file_dict()
                cond = xpdf_server_dict.get(XpdfServer, ['_no_file_']) != ['_no_file_']
                debug_file.write("XPDF SERVER DICT="+str(xpdf_server_dict)+"\n")
                debug_file.write("COND="+str(cond)+":"+str(reload_on_error)+":"+str(bang)+"\n")
                debug_file.write("COND="+str( not reload_on_error or bang )+"\n")
                debug_file.write(str(xpdf_server_dict)+"\n")
                if start == 1:
                    run=['xpdf']
                    run.extend(viewer_opt)
                    run.append(output_fp)
                    debug_file.write("D1: "+str(run)+"\n")
                    subprocess.Popen(run)
                elif cond and ( reload_on_error or latex_returncode == 0 or bang ):
                    run=['xpdf', '-remote', XpdfServer, '-reload']
                    subprocess.Popen(run, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
                    debug_file.write("D2: "+str(['xpdf',  '-remote', XpdfServer, '-reload'])+"\n")
            else:
                if start >= 1:
                    run=[viewer]
                    run.extend(viewer_opt)
                    run.append(output_fp)
                    debug_file.write("RUN "+str(run)+"\n")
                    subprocess.Popen(run, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
                if start == 2:
                    vim.eval("atplib#SyncTex()")

####################################
#
#       Clean:
#
####################################
        except Exception:
            error_str=re.sub("'", "''",re.sub('"', '\\"', traceback.format_exc()))
            traceback.print_exc(None, debug_file)
            vim.eval("atplib#callback#Echo(\"[ATP:] error in compile.py, catched python exception:\n"+error_str+"[ATP info:] this error message is recorded in compile.py.log under g:atp_TempDir\",'echo','ErrorMsg')")

# 	cleanup(debug_file)
#         return(latex_returncode)

LatexThread().start()
ENDPYTHON
endfunction "}}}
" {{{ atplib#compiler#tex [test function]
function! atplib#compiler#tex()
" Notes:
" this goes well untill status line is calling functions or functions which
" are called via autocommands. Strange errors occur, for example: 
" Error detected while processing function <SNR>106_HighlightMatchingPair..LatexBox_InComment:
" line 3:
" E121: Undefined variable: a:var 
" and other similar errors. Mainly (if not only) errors E121.
python << ENDPYTHON
import vim, threading
import sys, errno, os.path, shutil, subprocess, psutil, re, tempfile, optparse, glob
import traceback, atexit

from os import chdir, mkdir, putenv, devnull
from collections import deque

def latex_progress_bar(cmd):
# Run latex and send data for progress bar,

    child = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    # If I remove the code below and only put child.wait() 
    # then vim crashes.
    pid   = child.pid
    vim.eval("atplib#callback#LatexPID("+str(pid)+")")
    stack = deque([])
    while True:
        try:
            out = child.stdout.read(1).decode()
        except UnicodeDecodeError:
            out = ""
        if out == '' and child.poll() != None:
            break
        if out != '':
            stack.append(out)

            if len(stack)>10:
                stack.popleft()
            match = re.match('\[(\n?\d(\n|\d)*)({|\])',str(''.join(stack)))
            if match:
                vim.eval("atplib#callback#ProgressBar("+match.group(1)[match.start():match.end()]+","+str(pid)+")")
    child.wait()
    vim.eval("atplib#callback#ProgressBar('end',"+str(pid)+")")
    vim.eval("atplib#callback#PIDsRunning(\"b:atp_LatexPIDs\")")
    return child

class LatexThread( threading.Thread ):
    def run( self ):

        file=vim.eval("b:atp_MainFile")
	latex_progress_bar(['pdflatex', file])
LatexThread().start()
ENDPYTHON
endfunction "}}}
" AUTOMATIC TEX PROCESSING:
" {{{ atplib#compiler#auTeX
" This function calls the compilers in the background. It Needs to be a global
" function (it is used in options.vim, there is a trick to put function into
" a dictionary ... )

function! atplib#compiler#auTeX(...)

    if !exists("b:atp_changedtick")
	let b:atp_changedtick = b:changedtick
    endif

    if g:atp_debugauTeX
	echomsg "*****************"
	echomsg "b:atp_changedtick=".b:atp_changedtick." b:changedtick=".b:changedtick
    endif

    if mode() == 'i' && b:atp_updatetime_insert == 0 ||
		\ mode()=='n' && b:atp_updatetime_normal == 0
	if g:atp_debugauTeX
	    echomsg "autex is off for the mode: ".mode()
	endif
	return "autex is off for the mode: ".mode()." (see :help mode())"
    endif

    if mode() == 'i' && g:atp_noautex_in_math && atplib#IsInMath()
	return "noautex in math mode"
    endif


    " Wait if the compiler is running. The problem is that CursorHoldI autocommands
    " are not triggered more than once after 'updatetime'.
"     if index(split(g:atp_autex_wait, ','), mode()) != -1
" " 	\ !b:atp_autex_wait
" 	if g:atp_Compiler == "python"
" 	    call atplib#callback#PIDsRunning("b:atp_PythonPIDs")
" 	else
" 	    call atplib#callback#PIDsRunning("b:atp_LatexPIDs")
" 	endif
" 	call atplib#callback#PIDsRunning("b:atp_BibtexPIDs")
" 	echo string(b:atp_BibtexPIDs)
" 	if g:atp_Compiler == "python" && len(b:atp_PythonPIDs) ||
" 	    \ g:atp_Compiler == "bash" && len(b:atp_LatexPIDs) ||
" 	    \ len(b:atp_BibtexPIDs)
" " 	    unlockvar b:atp_autex_wait
" " 	    let b:atp_autex_wait=1
" " 	    lockvar b:atp_autex_wait
" 	    if g:atp_debugauTeX
" 		echomsg "autex wait"
" 	    endif
" 	    return
" 	endif
" "     else
" " 	unlockvar b:atp_autex_wait
" " 	let b:atp_autex_wait=0
" " 	lockvar b:atp_autex_wait
"     endif


    " Using vcscommand plugin the diff window ends with .tex thus the autocommand
    " applies but the filetype is 'diff' thus we can switch tex processing by:
    if &l:filetype !~ "tex$"
	echo "wrong file type"
	return "wrong file type"
    endif

    let atp_MainFile	= atplib#FullPath(b:atp_MainFile)

"     let mode 	= ( g:atp_DefaultDebugMode == 'verbose' ? 'debug' : g:atp_DefaultDebugMode )
    let mode	= substitute(t:atp_DebugMode, 'verbose$', 'debug', '')

    if !b:atp_autex
	if g:atp_debugauTeX
	   echomsg "autex is off"
	endif
	return "autex is off"
    endif

    " If the file (or input file is modified) compile the document 
    if filereadable(expand("%"))
" 	if !exists("b:atp_changedtick")
" 	    let b:atp_changedtick = b:changedtick
" 	endif
	if g:atp_Compare ==? "changedtick"
	    let cond = ( b:changedtick != b:atp_changedtick )
	else
	    let cond = ( atplib#compiler#compare(readfile(expand("%"))) )
	endif
	if g:atp_debugauTeX
	    let g:cond=cond
	    if g:atp_debugauTeX
		echomsg  "COND=".cond
	    endif
	endif
	if cond
	    " This is for changedtick only
	    let b:atp_changedtick = b:changedtick + 1
	    " +1 because atplib#compiler#Compiler saves the file what increases b:changedtick by 1.
	    " this is still needed as I use not nesting BufWritePost autocommand to set
	    " b:atp_changedtick (by default autocommands do not nest). Alternate solution is to
	    " run atplib#compiler#AuTeX() with nested autocommand (|autocmd-nested|). But this seems
	    " to be less user friendly, nested autocommands allows only 10 levels of
	    " nesting (which seems to be high enough).
	    
"
" 	if atplib#compiler#NewCompare()
	    if g:atp_Compiler == 'python'
		if b:atp_autex == 1
" 		    if g:atp_devversion == 0
			call atplib#compiler#PythonCompiler(0, 0, b:atp_auruns, mode, "AU", atp_MainFile, "")
" 		    else
" 			call atplib#compiler#ThreadedCompiler(0, 0, b:atp_auruns, mode, "AU", atp_MainFile, "")
" 		    endif
		else
		    call atplib#compiler#LocalCompiler("n")
		endif
	    else
		call atplib#compiler#Compiler(0, 0, b:atp_auruns, mode, "AU", atp_MainFile, "")
	    endif
	    redraw
	    if g:atp_debugauTeX
		echomsg "compile" 
	    endif
	    return "compile" 
	endif
    " if compiling for the first time
    else
	try 
	    " Do not write project script file while saving the file.
	    let atp_ProjectScript	= ( exists("g:atp_ProjectScript") ? g:atp_ProjectScript : -1 )
	    let g:atp_ProjectScript	= 0
	    w
	    if atp_ProjectScript == -1
		unlet g:atp_ProjectScript
	    else
		let g:atp_ProjectScript	= atp_ProjectScript
	    endif
	catch /E212:/
	    echohl ErrorMsg
	    if g:atp_debugauTeX
		echomsg expand("%") . "E212: Cannon open file for writing"
	    endif
	    echohl None
	    if g:atp_debugauTeX
		echomsg " E212"
	    endif
	    return " E212"
	catch /E382:/
	    " This option can be set by VCSCommand plugin using VCSVimDiff command
	    if g:atp_debugauTeX
		echomsg " E382"
	    endif
	    return " E382"
	endtry
	if g:atp_Compiler == 'python'
	    call atplib#compiler#PythonCompiler(0, 0, b:atp_auruns, mode, "AU", atp_MainFile, "")
	else
	    call atplib#compiler#Compiler(0, 0, b:atp_auruns, mode, "AU", atp_MainFile, "")
	endif
	redraw
	if g:atp_debugauTeX
	    echomsg "compile for the first time"
	endif
	return "compile for the first time"
    endif
    if g:atp_debugauTeX
	echomsg "files does not differ"
    endif
    return "files does not differ"
endfunction
"}}}

" Related Functions
" {{{ atplib#compiler#TeX

" a:runs	= how many consecutive runs
" a:1		= one of 'default','silent', 'debug', 'verbose'
" 		  if not specified uses 'default' mode
" 		  (g:atp_DefaultDebugMode).
function! atplib#compiler#TeX(runs, bang, ...)

"     if a:bang == "!"
" 	call atplib#compiler#LocalCompiler("n")
" 	return
"     endif
    let atp_MainFile	= atplib#FullPath(b:atp_MainFile)

    if !exists("t:atp_DebugMode")
	let t:atp_DebugMode = g:atp_DefaultDebugMode
    endif

    if a:0 >= 1
	let mode = ( a:1 != 'default' ? a:1 : t:atp_DebugMode )
    else
	let mode = t:atp_DebugMode
    endif

    let match = matchlist(mode, '^\(auto\)\?\(.*$\)')
    let auto = match[1]
    let mode = match[2]
    if mode =~# '^s\%[ilent]$'
	let mode = 'silent'
    elseif mode =~# '^d\%[ebug]$'
	let mode = 'debug'
    elseif mode =~# 'D\%[ebug]$'
	let mode = 'Debug'
    elseif mode =~#  '^v\%[erbose]$'
	let mode = 'verbose'
    else
	let mode = t:atp_DebugMode
    endif
    let mode = auto . mode
    let g:mode_0 = mode

    for cmd in keys(g:CompilerMsg_Dict) 
	if b:atp_TexCompiler =~ '^\s*' . cmd . '\s*$'
	    let Compiler = g:CompilerMsg_Dict[cmd]
	    break
	else
	    let Compiler = b:atp_TexCompiler
	endif
    endfor

    if l:mode != 'silent'
	if a:runs > 2 && a:runs <= 5
	    echo "[ATP:] ".Compiler . " will run " . a:1 . " times."
	elseif a:runs == 2
	    echo "[ATP:] ".Compiler . " will run twice."
	elseif a:runs == 1
	    echo "[ATP:] ".Compiler . " will run once."
	elseif a:runs > 5
	    echo "[ATP:] ".Compiler . " will run " . s:runlimit . " times."
	endif
    endif
    if g:atp_Compiler == 'python'
"         if g:atp_devversion == 0
"             call atplib#compiler#PythonCompiler(0,0, a:runs, mode, "COM", atp_MainFile, "")
            call atplib#compiler#PythonCompiler(0,0, a:runs, mode, "COM", atp_MainFile, a:bang)
"         else
"             call atplib#compiler#ThreadedCompiler(0,0, a:runs, mode, "COM", atp_MainFile, "")
"             call atplib#compiler#ThreadedCompiler(0,0, a:runs, mode, "COM", atp_MainFile, a:bang)
"         endif
    else
	call atplib#compiler#Compiler(0,0, a:runs, mode, "COM", atp_MainFile, a:bang)
    endif
endfunction
" command! -buffer -count=1	VTEX		:call atplib#compiler#TeX(<count>, 'verbose') 
"}}}
"{{{ atplib#compiler#DebugComp()
function! atplib#compiler#DebugComp(A,L,P)
    return "silent\ndebug\nDebug\nverbose"
endfunction "}}}
"{{{ atplib#compiler#Bibtex
function! atplib#compiler#SimpleBibtex()
    let bibcommand 	= b:atp_BibCompiler." "
    let atp_MainFile	= atplib#FullPath(b:atp_MainFile)
    if b:atp_BibCompiler =~ '^\s*biber\>'
	let file	= fnamemodify(resolve(atp_MainFile),":t:r")
    else
	let file	= fnamemodify(resolve(atp_MainFile),":t:r") . ".aux"
    endif
    let auxfile	= fnamemodify(resolve(atp_MainFile),":t:r") . ".aux"
    " When oupen_out = p (in texmf.cnf) bibtex can only open files in the working
    " directory and they should no be given with full path:
    "  		p (paranoid)   : as `r' and disallow going to parent directories, and
    "                  		 restrict absolute paths to be under $TEXMFOUTPUT.
    let saved_cwd	= getcwd()
    exe "lcd " . fnameescape(b:atp_OutDir)
    let g:cwd = getcwd()
    if filereadable(auxfile)
	let command	= bibcommand . shellescape(file)
	let b:atp_BibtexOutput=system(command)
	let b:atp_BibtexReturnCode=v:shell_error
	echo b:atp_BibtexOutput
    else
	echo "[ATP:] aux file " . auxfile . " not readable."
    endif
    exe "lcd " . fnameescape(saved_cwd)
endfunction

function! atplib#compiler#Bibtex(bang, ...)
    if a:0 >= 1 && a:1 =~# '^o\%[utput]$'
	redraw!
	if exists("b:atp_BibtexReturnCode")
	    echo "[Bib:] BibTeX returned with exit code " . b:atp_BibtexReturnCode
	endif
	if exists("b:atp_BibtexOutput")
	    echo substitute(b:atp_BibtexOutput, '\(^\zs\|\n\)', '\1       ', "g")
	else
	    echo "No BibiTeX output."
	endif
	return
    elseif a:bang == ""
	call atplib#compiler#SimpleBibtex()
	return
    endif

    let atp_MainFile	= atplib#FullPath(b:atp_MainFile)
    let g:a=a:0

    if a:0 >= 1
	let mode = ( a:1 != 'default' ? a:1 : t:atp_DebugMode )
    else
	let mode = t:atp_DebugMode
    endif

    if mode =~# '^s\%[ilent]$'
	let mode = 'silent'
    elseif mode =~# '^d\%[ebug]$'
	let mode = 'debug'
    elseif mode =~# 'D\%[ebug]$'
	let mode = 'Debug'
    elseif mode =~#  '^v\%[erbose]$'
	let mode = 'verbose'
    else
	let mode = t:atp_DebugMode
    endif

    if g:atp_Compiler == 'python'
"         if g:atp_devversion == 0
            call atplib#compiler#PythonCompiler(1, 0, 0, mode, "COM", atp_MainFile, "")
"         else
"             call atplib#compiler#ThreadedCompiler(1, 0, 0, mode, "COM", atp_MainFile, "")
"         endif
    else
	call atplib#compiler#Compiler(1, 0, 0, mode, "COM", atp_MainFile, "")
    endif
endfunction
function! atplib#compiler#BibtexComp(A,L,P)
	return "silent\ndebug\nDebug\nverbose\noutput"
endfunction
"}}}

" Show Errors Function
" (some error tools are in various.vim: ':ShowErrors o')
" {{{ SHOW ERRORS
"
" this functions sets errorformat according to the flag given in the argument,
" possible flags:
" e	- errors (or empty flag)
" w	- all warning messages (LaTeX warning, Citation warnings, Reference Warnings, Package warnings)
" c	- citation warning messages
" r	- reference warning messages
" f	- font warning messages
" fi	- font warning and info messages
" F	- files
" o	- open log file
" h	- overfull and underfull \hbox /g:atp_ParseLog only/
" p	- package info messages ('Package \w\+ Info: ') /g:atp_ParseLog only/
" P	- packages (lines which start with 'Package: ')

" {{{ atplib#compiler#SetErrorFormat
" first argument is a word in flags 
" the default is a:1=e /show only error messages/
function! atplib#compiler#SetErrorFormat(cgetfile,...)

    " Get the bufnr of tex file corresponding to the &l:errorfile
    let bufnr 	= bufnr(fnamemodify(&l:errorfile, ":r").".tex")
    let carg	= !exists("w:quickfix_title") && exists("b:atp_ErrorFormat")
		\ ? b:atp_ErrorFormat 
		\ : getbufvar((bufnr), "atp_ErrorFormat")
    let atp_ErrorFormat = ( exists("b:atp_ErrorFormat") ? b:atp_ErrorFormat : getbufvar((bufnr), "atp_ErrorFormat") )

    " This a:cgetfile == 1 only if run by the command :ErrorFormat 
    let efm = ( a:0 >= 1 ? a:1 : '' )
    if efm == "" || a:0 == 0
	echo "[ATP:] current error format: ".atp_ErrorFormat
	return
    endif

    let carg_raw = ( a:0 >= 1 ? a:1 : g:atp_DefaultErrorFormat )
    let carg_lists = split(carg_raw, '\ze[+-]')

    let g:carg_lists = carg_lists
    for carg_r in carg_lists
	let carg_list= split(carg_r, '\zs')
	if carg_list[0] =~ '^[+-]$'
	    let add=remove(carg_list,0)
	else
	    let add=0
	endif
	for i in range(0, len(carg_list)-2)
	    if carg_list[i] == 'f' && get(carg_list,i+1, "") == "i"
		call remove(carg_list, i+1)
		let carg_list[i]="fi"
	    endif
	endfor

	if carg_r =~ '^+'
	    for flag in carg_list
		if flag !=# 'f' && atp_ErrorFormat !~# flag || flag == 'f' && atp_ErrorFormat !~# 'fi\@!'
		    let carg .= flag
		endif
	    endfor
	elseif carg_r =~ '^-'
	    for flag in carg_list
		if flag !=# 'f'
		    let carg=substitute(carg, '\C'.flag, '', 'g')
		else
		    let carg=substitute(carg, '\Cfi\@!', '', 'g')
		endif
	    endfor
	else
	    let carg=carg_r
	endif
    endfor
    let b:atp_ErrorFormat = carg
    if exists("w:quickfix_title")
	call setbufvar(bufnr, "atp_ErrorFormat", carg)
    endif

    let &l:errorformat=""
    if ( carg =~ 'e' || carg =~? 'all' ) 
	if g:atp_ParseLog
	    let efm = 'LaTeX\ %trror::%f::%l::%c::%m'
	else
	    let efm = "%E!\ LaTeX\ Error:\ %m,\%E!\ %m,%E!pdfTeX Error:\ %m"
	endif
	if &l:errorformat == ""
	    let &l:errorformat= efm
	else
	    let &l:errorformat= &l:errorformat . "," . efm
	endif
    endif
    if ( carg =~ 'w' || carg =~? 'all' )
	if g:atp_ParseLog
	    let efm = 'LaTeX\ %tarning::%f::%l::%c::%m,Citation\ %tarning::%f::%l::%c::%m,Reference\ LaTeX\ %tarning::%f::%l::%c::%m,Package %tarning::%f::%l::0::%m'
	else
	    let efm='%WLaTeX\ %tarning:\ %m\ on\ input\ line\ %l%.,
			\%WLaTeX\ %.%#Warning:\ %m,
	    		\%Z(Font) %m\ on\ input\ line\ %l%.,
			\%+W%.%#\ at\ lines\ %l--%*\\d'
	endif
" 	let efm=
" 	    \'%+WLaTeX\ %.%#Warning:\ %.%#line\ %l%.%#,
" 	    \%+W%.%#\ at\ lines\ %l--%*\\d,
" 	    \%WLaTeX\ %.%#Warning:\ %m'
	if &l:errorformat == ""
	    let &l:errorformat=efm
	else
	    let &l:errorformat= &l:errorformat . ',' . efm
" 	    let &l:errorformat= &l:errorformat . ',%+WLaTeX\ %.%#Warning:\ %.%#line\ %l%.%#,
" 			\%WLaTeX\ %.%#Warning:\ %m,
" 			\%+W%.%#\ at\ lines\ %l--%*\\d'
	endif
    endif
    if g:atp_ParseLog && ( carg =~# 'h' || carg =~? 'all' )
	let efm = "hbox %tarning::%f::%l::0::%m"
	if &l:errorformat == ""
	    let &l:errorformat=efm
	else
	    let &l:errorformat= &l:errorformat . ',' . efm
	endif
    endif
    if ( carg =~ '\Cc' || carg =~? 'all' )
" NOTE:
" I would like to include 'Reference/Citation' as an error message (into %m)
" but not include the 'LaTeX Warning:'. I don't see how to do that actually. 
" The only solution, that I'm aware of, is to include the whole line using
" '%+W' but then the error messages are long and thus not readable.
	if g:atp_ParseLog
	    let efm = "Citation\ %tarning::%f::%l::%c::%m"
	else
	    let efm = "%WLaTeX\ Warning:\ Citation\ %m\ on\ input\ line\ %l%.%#"
	endif
	if &l:errorformat == ""
	    let &l:errorformat = efm
	else
	    let &l:errorformat = &l:errorformat.",".efm
	endif
    endif
    if ( carg =~ '\Cr' || carg =~? 'all' )
	if g:atp_ParseLog
	    let efm = "Reference\ LaTeX\ %tarning::%f::%l::%c::%m"
	else
	    let efm = "%WLaTeX\ Warning:\ Reference %m on\ input\ line\ %l%.%#,%WLaTeX\ %.%#Warning:\ Reference %m,%C %m on input line %l%.%#"
	endif
	if &l:errorformat == ""
	    let &l:errorformat = efm
	else
	    let &l:errorformat = &l:errorformat.",".efm
	endif
    endif
    if carg =~ '\Cf' || carg =~# 'All'
	if g:atp_ParseLog
	    let efm = "LaTeX\ Font\ %tarning::%f::%l::%c::%m"
	else
	    let efm = "%WLaTeX\ Font\ Warning:\ %m,%Z(Font) %m on input line %l%.%#"
	endif
	if &l:errorformat == ""
	    let &l:errorformat = efm
	else
	    let &l:errorformat = &l:errorformat.",".efm
	endif
    endif
    if carg =~ '\Cfi' || carg =~# 'All'
	if g:atp_ParseLog
	    let efm = 'LaTeX\ Font %tnfo::%f::%l::%c::%m'
	else
	    let efm = '%ILatex\ Font\ Info:\ %m on input line %l%.%#,
				\%ILatex\ Font\ Info:\ %m,
				\%Z(Font) %m\ on input line %l%.%#,
				\%C\ %m on input line %l%.%#'
	endif
	if &l:errorformat == ""
	    let &l:errorformat = efm
	else
	    let &l:errorformat = &l:errorformat.','.efm
	endif
    endif
    if carg =~ '\CF' || carg =~# 'All'
	if g:atp_ParseLog
	    let efm = "%tnput File::%f::%l::%c::%m,%tnput Package::%f::%l::%c::%m"
	else
	    let efm = '%+P)%#%\\s%#(%f,File: %m,Package: %m,Document Class: %m,LaTeX2e %m'
	endif
	if &l:errorformat == ""
	    let &l:errorformat = efm
	else
	    let &l:errorformat = &l:errorformat . ',' . efm
	endif
    endif
    if g:atp_ParseLog && (carg =~ '\Cp' || carg =~# 'All')
	let efm = "Package %tnfo::%f::%l::0::%m"
	if &l:errorformat == ""
	    let &l:errorformat = efm
	else
	    let &l:errorformat = &l:errorformat.','.efm
	endif
    endif
    if carg =~ '\CP' || carg =~# 'All'
	if g:atp_ParseLog
	    let efm = "Input %tackage::%f::0::0::%m"
	else
	    let efm = 'Package: %m'
	endif
	if &l:errorformat == ""
	    let &l:errorformat = efm
	else
	    let &l:errorformat = &l:errorformat.','.efm
	endif
    endif
    if &l:errorformat != "" && !g:atp_ParseLog

" 	let pm = ( g:atp_show_all_lines == 1 ? '+' : '-' )

" 	let l:dont_ignore = 0
" 	if carg =~ '\CA\cll'
" 	    let l:dont_ignore = 1
" 	    let pm = '+'
" 	endif

	let l:dont_ignore= 1
	let pm = '+'

	let &l:errorformat = &l:errorformat.",
			    \%-C<%.%#>%.%#,
			    \%-Zl.%l\ ,
		    	    \%-Zl.%l\ %m,
			    \%-ZI've inserted%.%#,
			    \%-ZThe control sequence%.%#,
			    \%-ZYour command was ignored%.%#,
			    \%-ZYou've closed more groups than you opened%.%#,
			    \%-ZThe `$' that I just saw%.%#,
			    \%-ZA number should have been here%.%#,
			    \%-ZI'm ignoring this;%.%#,
			    \%-ZI suspect you've forgotten%.%#,
			    \%-GSee LaTeX%.%#,
			    \%-GType\ \ H\ <return>%m,
			    \%-C\\s%#%m,
			    \%-C%.%#-%.%#,
			    \%-C%.%#[]%.%#,
			    \%-C[]%.%#,
			    \%-C%.%#%[{}\\]%.%#,
			    \%-G ...%.%#,
			    \%-G%.%#\ (C)\ %.%#,
			    \%-G(see\ the\ transcript%.%#),
			    \%-G\\s%#,
			    \%-G%.%#"
" These two appeared before l.%l (cannot be -Z):
" 			    \%-GSee LaTeX%.%#,
" 			    \%-GType\ \ H\ <return>%m,
	let &l:errorformat = &l:errorformat.",
			    \%".pm."O(%*[^()])%r,
			    \%".pm."O%*[^()](%*[^()])%r,
			    \%".pm."P(%f%r,
			    \%".pm."P\ %\\=(%f%r,
			    \%".pm."P%*[^()](%f%r,
			    \%".pm."P[%\\d%[^()]%#(%f%r"
	let &l:errorformat = &l:errorformat.",
			    \%".pm."Q)%r,
			    \%".pm."Q%*[^()])%r,
			    \%".pm."Q[%\\d%*[^()])%r"
    endif
    if a:cgetfile
	try
	    cgetfile
	    call atplib#compiler#FilterQuickFix()
	catch E40:
	endtry
	if g:atp_signs
	    call atplib#callback#Signs(bufnr("%"))
	endif
    endif
    let eventignore=&eventignore
    set eventignore=BufEnter,BufLeave
    if !exists("t:atp_QuickFixOpen")
	let t:atp_QuickFixOpen = 0
	windo let t:atp_QuickFixOpen+= ( &buftype == 'quickfix' )
	wincmd w
    endif
    if t:atp_QuickFixOpen
	let winnr=winnr()
	" Quickfix is opened, jump to it and change the size
	copen
	exe "resize ".min([atplib#qflength(), g:atp_DebugModeQuickFixHeight])
	exe winnr."wincmd w"
    endif
    let &eventignore=eventignore
    if add != "0"
	echo "[ATP:] current error format: ".b:atp_ErrorFormat 
    endif
endfunction
"}}}
function! atplib#compiler#FilterQuickFix() "{{{
    if !g:atp_ParseLog
	return
    endif
    let qflist = getqflist()
    call filter(qflist, 'v:val["type"] != ""')
    let new_qflist = []
    for item in qflist
	call remove(item, "valid")
	call add(new_qflist, item)
    endfor
    call setqflist(new_qflist)
endfunction
"}}}
"{{{ atplib#compiler#ShowErrors
" each argument can be a word in flags as for atplib#compiler#SetErrorFormat (except the
" word 'whole') + two other flags: all (include all errors) and ALL (include
" all errors and don't ignore any line - this overrides the variables
" g:atp_ignore_unmatched and g:atp_show_all_lines.
function! atplib#compiler#ShowErrors(...)
    " It is not atplib#compiler# because it is run from atplib#callback#CallBack()

    let errorfile	= &l:errorfile
    " read the log file and merge warning lines 
    " filereadable doesn't like shellescaped file names not fnameescaped. 
    " The same for readfile() and writefile()  built in functions.
    if !filereadable(errorfile)
	echohl WarningMsg
	echo "[ATP:] no error file: " . errorfile  
	echohl None
	return
    endif

    let log=readfile(errorfile)

    if !g:atp_ParseLog
	let nr=1
	for line in log
	    if line =~ "LaTeX Warning:" && get(log, nr, '') !~ "^$" 
		let newline=line . log[nr]
		let log[nr-1]=newline
		call remove(log,nr)
	    endif
	    let nr+=1
	endfor
	call writefile(log, errorfile)
    endif
    
    " set errorformat 
    let l:arg = ( a:0 >= 1 ? a:1 : b:atp_ErrorFormat )

    if l:arg =~# 'o'
	OpenLog
	return
    elseif l:arg =~ 'b'
	echo b:atp_BibtexOutput
	return
    endif
    call atplib#compiler#SetErrorFormat(0, l:arg)
    let show_message = ( a:0 >= 2 ? a:2 : 1 )

    " read the log file
    cgetfile
    call atplib#compiler#FilterQuickFix()

    " signs
    if g:atp_signs
	call atplib#callback#Signs(bufnr("%"))
    endif

    " final stuff
    if len(getqflist()) == 0 
	if show_message
	    echo "[ATP:] no errors :)"
	endif
	return ":)"
    else
	cl
	return 1
    endif
endfunction
"}}}
if !exists("*ListErrorsFlags")
function! atplib#compiler#ListErrorsFlags(A,L,P)
    if g:atp_ParseLog
	let flags = "e\nw\nr\nc\nf\nfi\nF\nh\np\nP\no\nall\nAll"
	return flags
    else
	let flags = "e\nw\nr\nc\nf\nfi\nF\no\nP\nall\nAll"
    endif
endfunction
endif
if !exists("*ListErrorsFlags_A")
function! atplib#compiler#ListErrorsFlags_A(A,L,P)
    " This has no o flag.
    if g:atp_ParseLog
	return "e\nw\nr\nc\nf\nfi\nF\nh\np\nP\nall\nAll"
    else
	return "e\nw\nr\nc\nf\nfi\nF\nP\nall\nAll"
    endif
endfunction
endif
"}}}
" vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1
autoload/atplib/complete.vim	[[[1
3257
" Title: 	Vim library for ATP filetype plugin.
" Author:	Marcin Szamotulski
" Email:	mszamot [AT] gmail [DOT] com
" Note:		This file is a part of Automatic Tex Plugin for Vim.
" URL:		https://launchpad.net/automatictexplugin
" Language:	tex


" Check If Closed:
" This functions checks if an environment is closed/opened.
" atplib#complete#CheckClosed {{{1
" check if last bpat is closed.
" starting from the current line, limits the number of
" lines to search. It returns 0 if the environment is not closed or the line
" number where it is closed (an env is cannot be closed in 0 line)

" ToDo: the two function should only check not commented lines!
"
" Method 0 makes mistakes if the pattern is \begin:\end, if
" \begin{env_name}:\end{env_names} rather no (unless there are nested
" environments in the same name.
" Method 1 doesn't make mistakes and thus is preferable.
" after testing I shall remove method 0
" Method 2 doesn't makes less mistakes than method 1 (which makes them :/) but it is only for
" brackets, returns >0 if the bracket is closed 0 if it is not. 
try
function! atplib#complete#CheckClosed(bpat, epat, line, col, limit,...)

"     NOTE: THIS IS MUCH FASTER !!! or SLOWER !!! ???            
"
"     let l:pos_saved=getpos(".") 
"     let l:cline=line(".")
"     if a:line != l:cline
" 	let l:col=len(getline(a:line))
" 	keepjumps call setpos(".",[0,a:line,l:col,0])
"     endif
"     let l:line=searchpair(a:bpat,'',a:epat,'nWr','',max([(a:line+a:limit),1]))
"     if a:line != l:cline
" 	keepjumps call setpos(".",l:pos_saved)
"     endif
"     return l:line

    let time = reltime()

    let l:method 		= ( a:0 >= 1 ? a:1 : 0 )
    let saved_pos		= getpos(".")
"     let l:count_method		= ( a:0 >= 2 ? a:2 : 1 )
    let l:len			= len(getbufline(bufname("%"),1,'$'))
    let l:nr			= a:line
    let cline			= line(".")

    if a:limit == "$" || a:limit == "-1"
	let l:limit=l:len-a:line
    else
	let l:limit=a:limit
    endif
    if g:atp_debugCheckClosed
	let g:saved_pos	= getpos(".")
	let g:nr	= a:line
	let g:bpat 	= a:bpat
	let g:limit	= l:limit
    endif


    if g:atp_debugCheckClosed == 1
	call atplib#Log("CheckClosed.log","", "init")
    endif

    if l:method==0 " {{{2
	while l:nr <= a:line+l:limit
	    let l:line=getline(l:nr)
	    " Remove comments:
	    let l:line=substitute(l:line, '\(\\\@<!\|\\\@<!\%(\\\\\)*\)\zs%.*', '', '')
	    if l:nr == a:line
		if strpart(l:line,getpos(".")[2]-1) =~ '\%(' . a:bpat . '.*\)\@<!' . a:epat
		    let g:time_CheckClosed=reltimestr(reltime(time))
		    return l:nr
		endif
	    else
		if l:line =~ '\%(' . a:epat . '.*\)\@<!' . a:bpat
		    let g:time_CheckClosed=reltimestr(reltime(time))
		    return 0
		elseif l:line =~ '\%(' . a:bpat . '.*\)\@<!' . a:epat 
		    let g:time_CheckClosed=reltimestr(reltime(time))
		    return l:nr
		endif
	    endif
	    let l:nr+=1
	endwhile

    elseif l:method==1 " {{{2

	let l:bpat_count	=0
	let l:epat_count	=0
	let l:begin_line	=getline(a:line)
	let l:begin_line_nr	=line(a:line)
	while l:nr <= a:line+l:limit
	    let l:line		=getline(l:nr)
	    if l:nr == a:line+l:limit
		let l:col	=match(l:line, '^.*'.a:epat.'\zs')
		if l:col != -1
		    let l:line	=strpart(l:line,0, l:col+1)
		endif
	    endif
	    let l:bpat_count+=atplib#count(l:line,a:bpat, 1)
	    let l:epat_count+=atplib#count(l:line,a:epat, 1)
	    if g:atp_debugCheckClosed
		call atplib#Log("CheckClosed.log", l:nr." l:bpat_count=".l:bpat_count." l:epat_count=".l:epat_count)
	    endif
	    if (l:bpat_count+1) == l:epat_count
		let g:time_CheckClosed=reltimestr(reltime(time))
		return l:nr
	    elseif l:bpat_count == l:epat_count && l:begin_line =~ a:bpat
		let g:time_CheckClosed=reltimestr(reltime(time))
		return l:nr
	    endif 
	    let l:nr+=1
	endwhile
	let g:time_CheckClosed=reltimestr(reltime(time))
	return 0

    elseif l:method==2 " {{{2
	" This is a special method for brackets.

	let l:bpat_count	=0
	let l:epat_count	=0
	let l:begin_line	= getline(a:line)
	let l:begin_line_nr	= line(a:line)


	" Find number of closed brackets which are opened before the a:line
	call cursor(a:line, 1)
	let l:closed_before_count = -1
	while line(".") < saved_pos[1] || line(".") == saved_pos[1] && col(".") <= saved_pos[2]
	    let test = searchpair(a:bpat, '', a:epat, 'W', '', saved_pos[1])
	    let l:closed_before_count += 1
	    if test == 0
		break
	    endif
	endwhile
	call cursor(saved_pos[1], saved_pos[2])
	if g:atp_debugCheckClosed
	    call atplib#Log("CheckClosed.log", "l:closed_before_count=".l:closed_before_count)
	    let g:nr_cc 	= l:nr
	    let g:line_cc 	= a:line
	    let g:limit_cc 	= l:limit
	endif
	while l:nr <= a:line+l:limit
	    let l:line		= getline(l:nr)
	    if l:nr == a:line+l:limit
		if g:atp_debugCheckClosed
		    call atplib#Log("CheckClosed.log", 'x1')
		endif
		let l:col	= match(l:line, '^.*'.a:epat.'\zs')
		if l:col != -1
		    let l:line	= strpart(l:line,0, l:col+1)
		endif
	    elseif l:nr == a:line
		let saved_pos 	= getpos(".")
		if g:atp_debugCheckClosed
		    call atplib#Log("CheckClosed.log", 'x2')
		    let g:epat = a:epat
		    let g:ps = getpos(".")
		endif
		call cursor(l:nr, 1)
		let l:col = 1
		" The following motion should go out any opened bracket which
		" is starts before a:line. It is far from perfect!
		" Indeed, it omits opened brackets!
" 		let [ nl, nc ] 	= searchpos('.*'.a:epat.'\zs', 'cn', cline)
" 		if nl != 0
" 		    let [l:nr, l:col] = [ nl, nc ]
" 		else
" 		    let [l:nr, l:col] = [ l:nr, 1 ]
" 		endif
		let l:line	= strpart(getline(l:nr), l:col-1)
	    endif
	    if l:nr == saved_pos[1]
		let cline	= strpart(getline(l:nr), 0, saved_pos[2]-1)
		if g:atp_debugCheckClosed 
		    let g:cline = cline
		endif
		let cpos_bpat_count = l:bpat_count+atplib#count(cline,a:bpat, 1)
		" (above we add 1 for the open one that we are checking)
		let cpos_epat_count = l:epat_count+atplib#count(cline,a:epat, 1)
		if g:atp_debugCheckClosed
		    call atplib#Log("CheckClosed.log", ">> cline=".cline."> cpos_bpat_count=".cpos_bpat_count." cpos_epat_count=".cpos_epat_count)
		endif
	    endif
	    " Strip comments:
	    let comment_match = match(l:line, '\%(\\\\\|\\\@<!\)%')
	    if comment_match != -1
		let l:line = strpart(l:line, 0, comment_match)
	    endif
	    call cursor(saved_pos[1], saved_pos[2])
	    let l:bpat_count+=atplib#count(l:line,a:bpat, 1)
	    let l:epat_count+=atplib#count(l:line,a:epat, 1)
	    let cond = l:epat_count - l:closed_before_count - l:bpat_count >= 0
	    if g:atp_debugCheckClosed
		call atplib#Log("CheckClosed.log", l:nr." l:bpat_count=".l:bpat_count." l:epat_count=".l:epat_count." ".l:line)
		if l:nr == saved_pos[1]
		    call atplib#Log("CheckClosed.log", l:nr." l:closed_before_count=".l:closed_before_count)
		endif
		if l:nr >= saved_pos[1]
		    call atplib#Log("CheckClosed.log", "cond (closed-opened)=".cond." value=".(l:epat_count - l:closed_before_count - l:bpat_count))
		endif	
	    endif
	    if l:nr >= saved_pos[1] && cond
		let g:time_CheckClosed=reltimestr(reltime(time))
		if g:atp_debugCheckClosed
		    let g:return = l:nr
		endif
		return l:nr
	    endif
	    let l:nr+=1
	endwhile
	let g:time_CheckClosed=reltimestr(reltime(time))
	return 0

    elseif l:method==3 " {{{2
	" This is a special method for brackets.
	" But it is too slow!

" 	silent echomsg "***************"
	let saved_pos 	= getpos(".")
	call cursor(a:line, a:col)
	let c_pos	= [a:line, a:col]
	let line	= a:line
" 	silent echomsg "a:line=".a:line." c_pos=".string(c_pos)." a:limit=".a:limit." cond=".string(a:line-c_pos[0] <= a:limit)
	while a:line-c_pos[0] <= a:limit
	    let pos=searchpairpos(a:bpat, '', a:epat, 'b')
" 	    silent echomsg string(pos)
	    if pos == [0, 0]
" 		silent echomsg "C1"
		call cursor(saved_pos[1], saved_pos[2])
		let g:time_CheckClosed=reltimestr(reltime(time))
		return c_pos[0]
	    endif
	    if pos == c_pos
" 		silent echomsg "C2"
		call cursor(saved_pos[1], saved_pos[2])
		let g:time_CheckClosed=reltimestr(reltime(time))
		return 0
	    endif
	    if atplib#CompareCoordinates(c_pos, pos)
" 		silent echomsg "C3"
		call cursor(saved_pos[1], saved_pos[2])
		let g:time_CheckClosed=reltimestr(reltime(time))
		return 0
	    endif
	    let c_pos = copy(pos)
	endwhile
" 	silent echomsg "C4"
	call cursor(saved_pos[1], saved_pos[2])
	let g:time_CheckClosed=reltimestr(reltime(time))
	return 1
    endif
endfunction
catch /E127:/
endtry
" }}}1
" {{{1 atplib#complete#CheckClosed_math
" This functions makes a test if in line math is closed. This works well with
" \(:\) and \[:\] but not yet with $:$ and $$:$$.  
" a:mathZone	= texMathZoneV or texMathZoneW or texMathZoneX or texMathZoneY
" The function return 1 if the mathZone is to be closed (i.e. it is not closed).
function! atplib#complete#CheckClosed_math(mathZone)
    let time 		= reltime()
    let synstack	= map(synstack(line("."), max([1, col(".")-1])), "synIDattr( v:val, 'name')")
    let check		= 0
    let patterns 	= { 
		\ 'texMathZoneV' : [ '\\\@<!\\(', 	'\\\@<!\\)' 	], 
		\ 'texMathZoneW' : [ '\\\@<!\\\[', 	'\\\@<!\\\]'	]}
    " Limit the search to the first \par or a blank line, if not then search
    " until the end of document:
    let stop_line	= search('\\par\|^\s*$', 'nW') - 1
    let stop_line	= ( stop_line == -1 ? line('$') : stop_line )

    " \(:\), \[:\], $:$ and $$:$$ do not accept blank lines, thus we can limit
    " searching/counting.
    
    " For \(:\) and \[:\] we use searchpair function to test if it is closed or
    " not.
    if (a:mathZone == 'texMathZoneV' || a:mathZone == 'texMathZoneW') && atplib#complete#CheckSyntaxGroups(['texMathZoneV', 'texMathZoneW'])
	if index(synstack, a:mathZone) != -1
	    let condition = searchpair( patterns[a:mathZone][0], '', patterns[a:mathZone][1], 'cnW', '', stop_line)
	    let check 	  = ( !condition ? 1 : check )
	else
	    let check	  = 0
	endif

    " $:$ and $$:$$ we are counting $ untill blank line or \par
    " to test if it is closed or not, 
    " then we return the number of $ modulo 2.
    elseif ( a:mathZone == 'texMathZoneX' || a:mathZone == 'texMathZoneY' ) && atplib#complete#CheckSyntaxGroups(['texMathZoneX', 'texMathZoneY'])
	let saved_pos	= getpos(".")
	let line	= line(".")	
	let l:count	= 0
	" count \$ if it is under the cursor
	if search('\\\@<!\$', 'Wc', stop_line)
	    let l:count += 1
	endif
	while line <= stop_line && line != 0
	    keepjumps let line	= search('\\\@<!\$', 'W', stop_line)
	    let l:count += 1
	endwhile
	keepjumps call setpos(".", saved_pos)
	let check	= l:count%2
    endif

    let g:time_CheckClosed_math=reltimestr(reltime(time))
    return check
endfunction
" atplib#complete#CheckClosed_syntax {{{1
" This function checks if a syntax group ends.
" Returns 1 if the syntax group doesn't ends before a:limit_line, a:limit_col line (last character is included).
"
" Note, this function is slower than atplib#complete#CheckClosed_math, which is designed
" for texMathZone[VWXY]. (call synstack(...) inside atplib#complete#CheckSyntaxGroups()
" is slow) - thus it is not used anymore.
function! atplib#complete#CheckClosed_syntax(syntax,limit_line, limit_col)
    let time		= reltime()
"     let whichwrap	= &whichwrap
"     setl whichwrap+=l
    let line		= line(".")
    let col		= col(".")
    let test		= atplib#complete#CheckSyntaxGroups(a:syntax)
    while ( line(".") < a:limit_line || line(".") == a:limit_line && col(".") <= a:limit_col ) && test
	normal! W
	let test	= atplib#complete#CheckSyntaxGroups(a:syntax)
    endwhile
    call cursor(line, col)
"     let &whichwrap	= whichwrap
    let g:time_CheckClosed_syntax=reltimestr(reltime(time))
    return test
endfunction
" }}}1
" atplib#complete#CheckOpened {{{1
" Usage: By default (a:0 == 0 || a:1 == 0 ) it returns line number where the
" environment is opened if the environment is opened and is not closed (for
" completion), else it returns 0. However, if a:1 == 1 it returns line number
" where the environment is opened, if we are inside an environment (it is
" opened and closed below the starting line or not closed at all), it if a:1
" = 2, it just check if env is opened without looking if it is closed (
" cursor position is important).
" a:1 == 0 first non closed
" a:1 == 2 first non closed by counting.

" this function doesn't check if sth is opened in lines which begins with '\\def\>'
" (some times one wants to have a command which opens an environment.

" Todo: write a faster function using searchpairpos() which returns correct
" values.
function! atplib#complete#CheckOpened(bpat,epat,line,limit)


"     this is almost good:    
"     let l:line=searchpair(a:bpat,'',a:epat,'bnWr','',max([(a:line-a:limit),1]))
"     return l:line

    let l:len=len(getbufline(bufname("%"),1,'$'))
    let l:nr=a:line

    if a:limit == "^" || a:limit == "-1"
	let l:limit=a:line-1
    else
	let l:limit=a:limit
    endif

    while l:nr >= a:line-l:limit && l:nr >= 1
	let l:line=getline(l:nr)
	    if l:nr == a:line
		    if substitute(strpart(l:line,0,getpos(".")[2]), a:bpat . '.\{-}' . a:epat,'','g')
				\ =~ a:bpat
			return l:nr
		    endif
	    else
" 		if l:check_mode == 0
" 		    if substitute(l:line, a:bpat . '.\{-}' . a:epat,'','g')
" 				\ =~ a:bpat
" 			" check if it is closed up to the place where we start. (There
" 			" is no need to check after, it will be checked anyway
" 			" b a serrate call in atplib#complete#TabCompletion.
" 			if !atplib#complete#CheckClosed(a:bpat,a:epat,l:nr,0,a:limit,0)
" 				" LAST CHANGE 1->0 above
" " 				let b:cifo_return=2 . " " . l:nr 
" 			    return l:nr
" 			endif
" 		    endif
" 		elseif l:check_mode == 1
		    if substitute(l:line, a:bpat . '.\{-}' . a:epat,'','g')
				\ =~ '\%(\\def\|\%(re\)\?newcommand\)\@<!' . a:bpat
			let l:check=atplib#complete#CheckClosed(a:bpat,a:epat,l:nr,0,a:limit,1)
			" if env is not closed or is closed after a:line
			if  l:check == 0 || l:check >= a:line
" 				let b:cifo_return=2 . " " . l:nr 
			    return l:nr
			endif
		    endif
" 		endif
	    endif
	let l:nr-=1
    endwhile
    return 0 
endfunction
" }}}1
" {{{1 atplib#complete#CheckSyntaxGroups
" This functions returns one if one of the environment given in the list
" a:zones is present in they syntax stack at line a:1 and column a:0.
" a:zones =	a list of zones
" a:1	  = 	line nr (default: current cursor line)
" a:2     =	column nr (default: column before the current cursor position)
" The function doesn't make any checks if the line and column supplied are
" valid /synstack() function returns 0 rather than [] in such a case/.
function! atplib#complete#CheckSyntaxGroups(zones,...)
    let line		= a:0 >= 1 ? a:1 : line(".")
    let col		= a:0 >= 2 ? a:2 : col(".")-1
    let col		= max([1, col])
    let zones		= copy(a:zones)

    let synstack_raw 	= synstack(line, col)
    if type(synstack_raw) != 3
	unlet synstack_raw
	return 0
    endif

    let synstack	= map(synstack_raw, 'synIDattr(v:val, "name")') 

    return max(map(zones, "count(synstack, v:val)"))
endfunction
" atplib#complete#CopyIndentation {{{1
function! atplib#complete#CopyIndentation(line)
    let raw_indent	= split(a:line,'\s\zs')
    let indent		= ""
    for char in raw_indent
	if char =~ '^\%(\s\|\t\)'
	    let indent.=char
	else
	    break
	endif
    endfor
    return indent
endfunction
"}}}1

" Close Environments And Brackets:
" atplib#complete#CloseLastEnvironment {{{1
" a:1 = i	(append before, so the cursor will  be after - the dafult)  
" 	a	(append after)
" a:2 = math 		the pairs \(:\), $:$, \[:\] or $$:$$ (if filetype is
" 						plaintex or b:atp_TexFlavor="plaintex")
" 	environment
" 			by the way, treating the math pairs together is very fast. 
" a:3 = environment name (if present and non zero sets a:2 = environment)	
" 	if one wants to find an environment name it must be 0 or "" or not
" 	given at all.
" a:4 = line and column number (in a vim list) where environment is opened
" a:5 = return only (only return the closing code (implemented only for a:2="math") 
" ToDo: Ad a highlight to messages!!! AND MAKE IT NOT DISAPPEAR SOME HOW?
" (redrawing doesn't help) CHECK lazyredraw. 
" Note: this function tries to not double the checks what to close if it is
" given in the arguments, and find only the information that is not given
" (possibly all the information as all arguments can be omitted).
function! atplib#complete#CloseLastEnvironment(...)

    let time = reltime()

    let l:com	= a:0 >= 1 ? a:1 : 'i'
    let l:close = a:0 >= 2 && a:2 != "" ? a:2 : 0
    if a:0 >= 3
	let l:env_name	= ( a:3 == "" ? 0 : a:3 )
	let l:close 	= ( a:3 != '' ? "environment" : l:close )
    else
	let l:env_name 	= 0
    endif
    let l:bpos_env	= ( a:0 >= 4 ? a:4 : [0, 0] )
    let return_only	= ( a:0 >= 5 ? a:5 : 0 )

    if g:atp_debugCloseLastEnvironment
	call atplib#Log('CloseLastEnvironment.log', '', 'init')
	let g:CLEargs 	= string(l:com) . " " . string(l:close) . " " . string(l:env_name) . " " . string(l:bpos_env)
	silent echo "args=".g:CLEargs
	let g:close 	= l:close
	let g:env_name	= l:env_name
	let g:bpos_env	= l:bpos_env
	call atplib#Log('CloseLastEnvironment.log', 'ARGS = '.g:CLEargs)
    endif

"   {{{2 find the begining line of environment to close (if we are closing
"   an environment)
    if l:env_name == 0 && ( l:close == "environment" || l:close == 0 ) && l:close != "math"

	let filter 	= 'strpart(getline(''.''), 0, col(''.'') - 1) =~ ''\\\@<!%'''

	" Check if and environment is opened (\begin:\end):
	" This is the slow part :( 0.4s)
	" Find the begining line if it was not given.
	if l:bpos_env == [0, 0]
	    " Find line where the environment is opened and not closed:
	    let l:bpos_env		= searchpairpos('\\begin\s*{', '', '\\end\s*{', 'bnW', 'searchpair("\\\\begin\s*{\s*".matchstr(getline("."),"\\\\begin\s*{\\zs[^}]*\\ze\}"), "", "\\\\end\s*{\s*".matchstr(getline("."), "\\\\begin\s*{\\zs[^}]*\\ze}"), "nW", "", "line(".")+g:atp_completion_limits[2]")',max([ 1, (line(".")-g:atp_completion_limits[2])]))
	endif

	let l:env_name		= matchstr(strpart(getline(l:bpos_env[0]),l:bpos_env[1]-1), '\\begin\s*{\s*\zs[^}]*\ze*\s*}')

    " if a:3 (environment name) was given:
    elseif l:env_name != "0" && l:close == "environment" 

	let l:bpos_env	= searchpairpos('\\begin\s*{'.l:env_name.'}', '', '\\end\s*{'.l:env_name.'}', 'bnW', '',max([1,(line(".")-g:atp_completion_limits[2])]))

    endif
"   }}}2
"   {{{2 if a:2 was not given (l:close = 0) we have to check math modes as
"   well.
    if ( l:close == "0" || l:close == "math" ) && l:bpos_env == [0, 0] 

	let stopline 		= search('^\s*$\|\\par\>', 'bnW')

	" Check if one of \(:\), \[:\], $:$, $$:$$ is opened using syntax
	" file. If it is fined the starting position.

	let synstack		= map(synstack(line("."),max([1, col(".")-1])), 'synIDattr(v:val, "name")')
	if g:atp_debugCloseLastEnvironment
	    let g:synstackCLE	= deepcopy(synstack)
	    let g:openCLE	= getline(".")[col(".")-1] . getline(".")[col(".")]
	    call atplib#Log('CloseLastEnvironment.log', "g:openCLE=".string(g:openCLE))
	    call atplib#Log('CloseLastEnvironment.log', 'synstack='.string(synstack))
	endif
	let bound_1		= getline(".")[col(".")-1] . getline(".")[col(".")] =~ '^\\\%((\|)\)$'
	let math_1		= (index(synstack, 'texMathZoneV') != -1 && !bound_1 ? 1  : 0 )   
	    if math_1
		if l:bpos_env == [0, 0]
		    let bpos_math_1	= searchpos('\%(\%(\\\)\@<!\\\)\@<!\\(', 'bnW', stopline)
		else
		    let bpos_math_1	= l:bpos_env
		endif
		let l:begin_line= bpos_math_1[0]
		let math_mode	= "texMathZoneV"
	    endif
	" the \[:\] pair:
	let bound_2		= matchstr(getline("."), ".", col(".")-1) . matchstr(getline("."), ".", col(".")) =~ '^\\\%(\[\|\]\)$'
	let math_2		= (index(synstack, 'texMathZoneW') != -1 && !bound_2 ? 1  : 0 )   
	    if math_2
		if l:bpos_env == [0, 0]
		    let bpos_math_2	= searchpos('\%(\%(\\\)\@<!\\\)\@<!\\[', 'bnW', stopline)
		else
		    let bpos_math_2	= l:bpos_env
		endif
		let l:begin_line= bpos_math_2[0]
		let math_mode	= "texMathZoneW"
	    endif
	" the $:$ pair:
	let bound_3		= matchstr(getline("."), ".", col(".")-1) =~ '^\$$'
	let math_3		= (index(synstack, 'texMathZoneX') != -1 && !bound_3 ? 1  : 0 )   
	    if math_3
		if l:bpos_env == [0, 0]
		    let bpos_math_3	= searchpos('\%(\%(\\\)\@<!\\\)\@<!\$\{1,1}', 'bnW', stopline)
		else
		    let bpos_math_3	= l:bpos_env
		endif
		let l:begin_line= bpos_math_3[0]
		let math_mode	= "texMathZoneX"
	    endif
	" the $$:$$ pair:
	let bound_4		= matchstr(getline("."), ".", col(".")-1) . matchstr(getline("."), ".", col(".")) =~ '^\$\$$'
	let math_4		= (index(synstack, 'texMathZoneY') != -1 && !bound_4 ? 1  : 0 )   
	    if math_4
		if l:bpos_env == [0, 0]
		    let bpos_math_4	= searchpos('\%(\%(\\\)\@<!\\\)\@<!\$\{2,2}', 'bnW', stopline)
		else
		    let bpos_math_4	= l:bpos_env
		endif
		let l:begin_line= bpos_math_4[0]
		let math_mode	= "texMathZoneY"
	    endif
	if g:atp_debugCloseLastEnvironment
	    let g:math 	= []
	    let g:bound = []
	    for i in [1,2,3,4]
		let g:begin_line = ( exists("begin_line") ? begin_line : 0 )
		let g:bound_{i} = bound_{i}
		call add(g:bound, bound_{i})
		let g:math_{i} = math_{i}
		call add(g:math, math_{i})
	    endfor
	    call atplib#Log('CloseLastEnvironment.log', "g:begin_line=".g:begin_line)
	    call atplib#Log('CloseLastEnvironment.log', "g:bound=".string(g:bound))
	    call atplib#Log('CloseLastEnvironment.log', "g:math=".string(g:math))
	    call atplib#Log('CloseLastEnvironment.log', "math_mode=".( exists("math_mode") ? math_mode : "None" ))
	endif
    elseif ( l:close == "0" || l:close == "math" )
	let string = matchstr(getline(l:bpos_env[0]), ".", l:bpos_env[1]-2) . matchstr(getline(l:bpos_env[0]), ".", l:bpos_env[1]-1) . matchstr(getline(l:bpos_env[0]), ".", l:bpos_env[1])
	let stop_line = search('\\par\|^\s*$\|\\\%(begin\|end\)\s*{', 'n')
	let [ math_1, math_2, math_3, math_4 ] = [ 0, 0, 0, 0 ]
	let saved_pos		= getpos(".")
	if string =~ '\\\@<!\\('
	    call cursor(l:bpos_env) 
	    " Check if closed:
	    let math_1 		= searchpair('\\(', '', '\\)', 'n', '', stop_line)
	    if !math_1
		let math_mode	= "texMathZoneV"
	    endif
	elseif string =~ '\\\@<!\\\['
	    call cursor(l:bpos_env) 
	    " Check if closed:
	    let math_2 		= searchpair('\\\[', '', '\\\]', 'n', '', stop_line)
	    if !math_2
		let math_mode	= "texMathZoneW"
	    endif
	elseif string =~ '\%(\\\|\$\)\@<!\$\$\@!'
	    " Check if closed: 	not implemented
	    let math_3 		= 0
	    let math_mode	= "texMathZoneX"
	elseif string =~ '\\\@<!\$\$'
	    " Check if closed: 	not implemented
	    let math_4 		= 0
	    let math_mode	= "texMathZoneY"
	endif
	call cursor([ saved_pos[1], saved_pos[2] ]) 
	if g:atp_debugCloseLastEnvironment
	    if exists("math_mode")
		let g:math_mode  	= math_mode
		call atplib#Log('CloseLastEnvironment.log', "math_mode=".math_mode)
	    endif
	    let g:math 	= []
	    let g:string = string
	    for i in [1,2,3,4]
		let g:begin_line = ( exists("begin_line") ? begin_line : 0 )
		let g:math_{i} = math_{i}
		call add(g:math, math_{i})
	    endfor
	    call atplib#Log('CloseLastEnvironment.log', "g:begin_line".g:begin_line)
	    call atplib#Log('CloseLastEnvironment.log', "g:math=".string(g:math))
	endif
	if exists("math_mode")
	    let l:begin_line 	= l:bpos_env[0]
	    if g:atp_debugCloseLastEnvironment
		call atplib#Log('CloseLastEnvironment.log', "math_mode=".math_mode)
		call atplib#Log('CloseLastEnvironment.log', "l:begin_line=".l:begin_line)
	    endif
	else
	    if g:atp_debugCloseLastEnvironment
		call atplib#Log('CloseLastEnvironment.log', "Given coordinates are closed.")
		redir END
	    endif
	    let g:time_CloseLastEnvironment = reltimestr(reltime(time))
	    return ''
	endif
    endif
"}}}2
"{{{2 set l:close if a:1 was not given.
if a:0 <= 1
" 	let l:begin_line=max([ l:begin_line_env, l:begin_line_imath, l:begin_line_dmath ])
    " now we can set what to close:
    " the synstack never contains two of the math zones: texMathZoneV,
    " texMathZoneW, texMathZoneX, texMathZoneY.
    if math_1 + math_2 + math_3 + math_4 >= 1
	let l:close = 'math'
    elseif l:env_name
	let l:close = 'environment'
    else
	if g:atp_debugCloseLastEnvironment
	    call atplib#Log('CloseLastEnvironment.log', "return: l:env_name=".string(l:env_name)." && math_1+...+math_4=".string(math_1+math_2+math_3+math_4))
	endif
	let g:time_CloseLastEnvironment = reltimestr(reltime(time))
	return ''
    endif
endif
if g:atp_debugCloseLastEnvironment
    let g:close = l:close
    call atplib#Log('CloseLastEnvironment.log', 'l:close='.l:close)
    call atplib#Log('CloseLastEnvironment.log', 'l:env_name='.l:env_name)
endif
let l:env=l:env_name
"}}}2

if l:close == "0" || l:close == 'math' && !exists("begin_line")
    if g:atp_debugCloseLastEnvironment
	call atplib#Log('CloseLastEnvironment.log', 'there was nothing to close')
    endif
    let g:time_CloseLastEnvironment = reltimestr(reltime(time))
    return ''
endif
if ( &filetype != "plaintex" && b:atp_TexFlavor != "plaintex" && exists("math_4") && math_4 )
    echohl ErrorMsg
    echomsg "[ATP:] $$:$$ in LaTeX are deprecated (this breaks some LaTeX packages)" 
    echomsg "       You can set b:atp_TexFlavor = 'plaintex', and ATP will ignore this. "
    echohl None
    if g:atp_debugCloseLastEnvironment
	call atplib#Log('CloseLastEnvironment.log', "return A")
    endif
    let g:time_CloseLastEnvironment = reltimestr(reltime(time))
    return  ''
endif
if l:env_name =~ '^\s*document\s*$'
    if g:atp_debugCloseLastEnvironment
	call atplib#Log('CloseLastEnvironment.log', "return B")
    endif
    let g:time_CloseLastEnvironment = reltimestr(reltime(time))
    return ''
endif
let l:cline	= getline(".")
let l:pos	= getpos(".")
if l:close == "math"
    let l:line	= getline(l:begin_line)
elseif l:close == "environment"
    let l:line	= getline(l:bpos_env[0])
endif

    if g:atp_debugCloseLastEnvironment
	let g:line = ( exists("l:line") ? l:line : 0 )
	call atplib#Log('CloseLastEnvironment.log', "g:line=".g:line)
    endif

" Copy the indentation of what we are closing.
let l:eindent=atplib#complete#CopyIndentation(l:line)
"{{{2 close environment
    if l:close == 'environment'
	" Info message
	redraw
" 	silent echomsg "[ATP:] closing " . l:env_name . " from line " . l:bpos_env[0]

	" Rules:
	" env & \[ \]: close in the same line 
	" unless it starts in a serrate line,
	" \( \): close in the same line. 
	"{{{3 close environment in the same line
	if l:line != "" && l:line !~ '^\s*\%(\$\|\$\$\|[^\\]\\%(\|\\\@<!\\\[\)\?\s*\\begin\s*{[^}]*}\s*\%((.*)\s*\|{.*}\s*\|\[.*\]\s*\)\{,3}\%(\s*\\label\s*{[^}]*}\s*\|\s*\\hypertarget\s*{[^}]*}\s*{[^}]*}\s*\)\{0,2}$'
	    " I use \[.*\] instead of \[[^\]*\] which doesn't work with nested
	    " \[:\] the same for {:} and (:).
" 	    	This pattern matches:
" 	    		^ $
" 	    		^ $$
" 	    		^ \(
" 	    		^ \[
" 	    		^ (one of above or space) \begin { env_name } ( args1 ) [ args2 ] { args3 } \label {label} \hypertarget {} {}
" 	    		There are at most 3 args of any type with any order \label and \hypertarget are matched optionaly.
" 	    		Any of these have to be followd by white space up to end of line.
	    "
	    " The line above cannot contain "\|^\s*$" pattern! Then the
	    " algorithm for placing the \end in right place is not called.
	    "
	    " 		    THIS WILL BE NEEDED LATER!
" 		    \ (l:close == 'display_math' 	&& l:line !~ '^\s*[^\\]\\\[\s*$') ||
" 		    \ (l:close == 'inline_math' 	&& (l:line !~ '^\s*[^\\]\\(\s*$' || l:begin_line == line("."))) ||
" 		    \ (l:close == 'dolar_math' 		&& l:cline =~ '\$')

	    " the above condition matches for the situations when we have to
	    " complete in the same line in four cases:
	    " l:close == environment, display_math, inline_math or
	    " dolar_math. 

	    " do not complete environments which starts in a definition.
" let b:cle_debug= (getline(l:begin_line) =~ '\\def\|\%(re\)\?newcommand') . " " . (l:begin_line != line("."))
" 	    if getline(l:begin_line) =~ '\\def\|\%(re\)\?newcommand' && l:begin_line != line(".")
"  		let b:cle_return="def"
" 		return b:cle_return
" 	    endif
	    if index(g:atp_no_complete, l:env) == '-1' &&
		\ !atplib#complete#CheckClosed('\%(%.*\)\@<!\\begin\s*{' . l:env,'\%(%.*\)\@<!\\end\s*{' . l:env,line("."),col("."),g:atp_completion_limits[2])
		if l:com == 'a'  
		    call setline(line("."), strpart(l:cline,0,getpos(".")[2]) . '\end{'.l:env.'}' . strpart(l:cline,getpos(".")[2]))
		    let l:pos=getpos(".")
		    let l:pos[2]=len(strpart(l:cline,0,getpos(".")[2]) . '\end{'.l:env.'}')+1
		    keepjumps call setpos(".",l:pos)
		elseif l:cline =~ '^\s*$'
		    call setline(line("."), l:eindent . '\end{'.l:env.'}' . strpart(l:cline,getpos(".")[2]-1))
		    let l:pos=getpos(".")
		    let l:pos[2]=len(strpart(l:cline,0,getpos(".")[2]-1) . '\end{'.l:env.'}')+1
		    keepjumps call setpos(".",l:pos)
		else
		    call setline(line("."), strpart(l:cline,0,getpos(".")[2]-1) . '\end{'.l:env.'}' . strpart(l:cline,getpos(".")[2]-1))
		    let l:pos=getpos(".")
		    let l:pos[2]=len(strpart(l:cline,0,getpos(".")[2]-1) . '\end{'.l:env.'}')+1
		    keepjumps call setpos(".",l:pos)
		endif
	    endif "}}}3
	"{{{3 close environment in a new line 
	else 

		if g:atp_debugCloseLastEnvironment
		    call atplib#Log('CloseLastEnvironment.log', 'close environment in a new line')
		endif

		" do not complete environments which starts in a definition.

		let l:error=0
		let l:prev_line_nr="-1"
		let l:cenv_lines=[]
		let l:nr=line(".")
		
		let l:line_nr=line(".")
		if g:atp_debugCloseLastEnvironment
		    call atplib#Log('CloseLastEnvironment.log', 'l:line_nr='.l:line_nr)
		endif

		" l:line_nr number of line which we complete
		" l:cenv_lines list of closed environments (we complete after
		" line number maximum of these numbers.

		let l:pos=getpos(".")
		let l:pos_saved=deepcopy(l:pos)
		if g:atp_debugCloseLastEnvironment
		    let g:pos_saved0 = copy(l:pos_saved)
		endif

		while l:line_nr >= 0
		    let [ l:line_nr, l:col_nr ]=searchpos('\%(%.*\)\@<!\\begin\s*{\zs', 'bW')
		    " match last environment openned in this line.
		    " ToDo: afterwards we can make it works for multiple openned
		    " envs.
		    let l:env_name=matchstr(getline(l:line_nr),'\%(%.*\)\@<!\\begin\s*{\zs[^}]*\ze}\%(.*\\begin\s*{[^}]*}\)\@!')
		    if g:atp_debugCloseLastEnvironment
			call atplib#Log('CloseLastEnvironment.log', 'WHILE l:env_name='.l:env_name)
		    endif
		    if index(g:atp_long_environments, l:env_name) != -1
			let l:limit=3
		    else
			let l:limit=2
		    endif
		    let l:close_line_nr=atplib#complete#CheckClosed('\%(%.*\)\@<!\\begin\s*{' . l:env_name, 
				\ '\%(%.*\)\@<!\\end\s*{' . l:env_name,
				\ l:line_nr, l:col_nr, g:atp_completion_limits[l:limit], 1)
		    if g:atp_debugCloseLastEnvironment
			call atplib#Log('CloseLastEnvironment.log', 'WHILE l:close_line_nr='.l:close_line_nr)
			call atplib#Log('CloseLastEnvironment.log', 'WHILE atplib#complete#CheckClosed args ='.l:line_nr.', '.l:col_nr.', '.g:atp_completion_limits[l:limit].', 1')
		    endif

		    if l:close_line_nr != 0
			call add(l:cenv_lines, l:close_line_nr)
		    else
			break
		    endif
		    if g:atp_debugCloseLastEnvironment
			call atplib#Log('CloseLastEnvironment.log', 'WHILE l:line_nr='.l:line_nr)
		    endif
		    let l:line_nr-=1
		endwhile

		keepjumps call setpos(".",l:pos)
			
		if getline(l:line_nr) =~ '\%(%.*\)\@<!\%(\\def\|\%(re\)\?newcommand\)' && l:line_nr != line(".")
" 		    let b:cle_return="def"
		    if g:atp_debugCloseLastEnvironment
			call atplib#Log('CloseLastEnvironmemt.log', 'return C')
		    endif
		    let g:time_CloseLastEnvironment = reltimestr(reltime(time))
		    return ''
		endif

		" get all names of environments which begin in this line
		let l:env_names=[]
		let l:line=getline(l:line_nr)
		while l:line =~ '\\begin\s*{' 
		    let l:cenv_begins = match(l:line,'\%(%.*\)\@<!\\begin{\zs[^}]*\ze}\%(.*\\begin\s{\)\@!')
		    let l:cenv_name = matchstr(l:line,'\%(%.*\)\@<!\\begin{\zs[^}]*\ze}\%(.*\\begin\s{\)\@!')
		    let l:cenv_len=len(l:cenv_name)
		    let l:line=strpart(l:line,l:cenv_begins+l:cenv_len)
		    call add(l:env_names,l:cenv_name)
		endwhile
		" thus we have a list of env names.
		
		" make a dictionary of lines where they closes. 
		" this is a list of pairs (I need the order!)
		let l:env_dict=[]

		" list of closed environments
		let l:cenv_names=[]

		if g:atp_debugCloseLastEnvironment
		    call atplib#Log('CloseLastEnvironment.log', 'l:env_names='.string(l:env_names))
		endif

		for l:uenv in l:env_names
		    let l:uline_nr=atplib#complete#CheckClosed('\%(%.*\)\@<!\\begin\s*{' . l:uenv . '}', 
				\ '\%(%.*\)\@<!\\end\s*{' . l:uenv . '}',
				\ l:line_nr, l:col_nr, g:atp_completion_limits[2])
		    call extend(l:env_dict,[ l:uenv, l:uline_nr])
		    if l:uline_nr != '0'
			call add(l:cenv_names,l:uenv)
		    endif
		endfor

		if g:atp_debugCloseLastEnvironment
		    call atplib#Log('CloseLastEnvironment.log', 'l:cenv_names='.string(l:cenv_names))
		endif
		
		" close unclosed environment

		" check if at least one of them is closed
		if len(l:cenv_names) == 0
		    let l:str=""
		    for l:uenv in l:env_names
			if index(g:atp_no_complete,l:uenv) == '-1'
			    let l:str.='\end{' . l:uenv .'}'
			endif
		    endfor
		    " l:uenv will remain the last environment name which
		    " I use!
		    " Do not append empty lines (l:str is empty if all l:uenv
		    " belongs to the g:atp_no_complete list.
		    if len(l:str) == 0
			if g:atp_debugCloseLastEnvironment
			    silent echo "return D"
			    redir END
			endif
			let g:time_CloseLastEnvironment = reltimestr(reltime(time))
			return ''
		    endif
		    let l:eindent=atplib#complete#CopyIndentation(getline(l:line_nr))
		    let l:pos=getpos(".")
		    if len(l:cenv_lines) > 0 

			let l:max=max(l:cenv_lines)
			let l:pos[1]=l:max+1
			" find the first closed item below the last closed
			" pair (below l:pos[1]). (I assume every env is in
			" a seprate line!
			let l:end=atplib#complete#CheckClosed('\%(%.*\)\@<!\\begin\s*{','\%(%.*\)\@<!\\end\s*{',
				    \ l:line_nr, l:col_nr, g:atp_completion_limits[2], 1)
			if g:atp_debugCloseLastEnvironment
			    let g:info= " l:max=".l:max." l:end=".l:end." line('.')=".line(".")." l:line_nr=".l:line_nr
			    call atplib#Log('CloseLastEnvironmemt.log', g:info)
			endif
			" if the line was found append just befor it.
			if l:end != 0 
				if line(".") <= l:max
				    if line(".") <= l:end
					call append(l:max, l:eindent . l:str)
					echomsg "[ATP:] closing " . l:env_name . " from line " . l:bpos_env[0] . " at line " . l:end+1  
					call setpos(".",[0,l:max+1,len(l:eindent.l:str)+1,0])
				    else
					call append(l:end-1, l:eindent . l:str)
					echomsg "[ATP:] closing " . l:env_name . " from line " . l:bpos_env[0] . " at line " . l:end+1 
					call setpos(".",[0,l:end,len(l:eindent.l:str)+1,0])
				    endif
				elseif line(".") < l:end
				    let [ lineNr, pos_lineNr ]	= getline(".") =~ '^\s*$' ? [ line(".")-1, line(".")] : [ line("."), line(".")+1 ]
				    call append(lineNr, l:eindent . l:str)
				    echomsg "[ATP:] closing " . l:env_name . " from line " . l:bpos_env[0] . " at line " . line(".")+1  
				    call setpos(".",[0, pos_lineNr,len(l:eindent.l:str)+1,0])
				elseif line(".") >= l:end
				    call append(l:end-1, l:eindent . l:str)
				    echomsg "[ATP:] closing " . l:env_name . " from line " . l:bpos_env[0] . " at line " . l:end
				    call setpos(".",[0,l:end,len(l:eindent.l:str)+1,0])
				endif
			else
			    if line(".") >= l:max
				call append(l:pos_saved[1], l:eindent . l:str)
				keepjumps call setpos(".",l:pos_saved)
				echomsg "[ATP:] closing " . l:env_name . " from line " . l:bpos_env[0] . " at line " . line(".")+1
				call setpos(".",[0,l:pos_saved[1]+1,len(l:eindent.l:str)+1,0])
			    elseif line(".") < l:max
				call append(l:max, l:eindent . l:str)
				echomsg "[ATP:] closing " . l:env_name . " from line " . l:bpos_env[0] . " at line " . l:max+1
				call setpos(".",[0,l:max+1,len(l:eindent.l:str)+1,0])
			    endif
			endif
		    else
			let l:pos[1]=l:line_nr
			let l:pos[2]=1
			" put cursor at the end of the line where not closed \begin was
			" found
			keepjumps call setpos(".",[0,l:line_nr,len(getline(l:line_nr)),0])
			let l:cline	= getline(l:pos_saved[1])
			if g:atp_debugCloseLastEnvironment
			    let g:cline		= l:cline
			    let g:pos_saved 	= copy(l:pos_saved)
			    let g:line		= l:pos_saved[1]
			endif
			let l:iline=searchpair('\\begin{','','\\end{','nW')
			if l:iline > l:line_nr && l:iline <= l:pos_saved[1]
			    call append(l:iline-1, l:eindent . l:str)
			    echomsg "[ATP:] closing " . l:env_name . " from line " . l:bpos_env[0] . " at line " . l:iline
			    let l:pos_saved[2]+=len(l:str)
			    call setpos(".",[0,l:iline,len(l:eindent.l:str)+1,0])
			else
			    if l:cline =~ '\\begin{\%('.l:uenv.'\)\@!'
				call append(l:pos_saved[1]-1, l:eindent . l:str)
				echomsg "[ATP:] closing " . l:env_name . " from line " . l:bpos_env[0] . " at line " . l:pos_saved[1]
				let l:pos_saved[2]+=len(l:str)
				call setpos(".",[0,l:pos_saved[1],len(l:eindent.l:str)+1,0])
			    elseif l:cline =~ '^\s*$'
				call append(l:pos_saved[1]-1, l:eindent . l:str)
				echomsg "[ATP:] closing " . l:env_name . " from line " . l:bpos_env[0] . " at line " . l:pos_saved[1]
				let l:pos_saved[2]+=len(l:str)
				call setpos(".",[0,l:pos_saved[1]+1,len(l:eindent.l:str)+1,0])
			    else
				call append(l:pos_saved[1], l:eindent . l:str)
				echomsg "[ATP:] closing " . l:env_name . " from line " . l:bpos_env[0] . " at line " . l:pos_saved[1]+1
				" Do not move corsor if: '\begin{env_name}<Tab>'
				if l:cline !~  '\\begin\s*{\s*\%('.l:uenv.'\)\s*}'
				    let l:pos_saved[2]+=len(l:str)
				    call setpos(".",[0,l:pos_saved[1]+1,len(l:eindent.l:str)+1,0])
				else
				    call setpos(".", l:pos_saved)
				endif
			    endif
			endif 
			if g:atp_debugCloseLastEnvironment
			    silent echo "return E"
			    redir END
			endif
			let g:time_CloseLastEnvironment = reltimestr(reltime(time))
			return ''
		    endif
		else
		    if g:atp_debugCloseLastEnvironment
			silent echo "return F"
			redir END
		    endif
		    let g:time_CloseLastEnvironment = reltimestr(reltime(time))
		    return ''
		endif
		unlet! l:env_names
		unlet! l:env_dict
		unlet! l:cenv_names
		unlet! l:pos 
		unlet! l:pos_saved
" 		if getline('.') =~ '^\s*$'
" 		    exec "normal dd"
		endif
    "}}}3
    "{{{2 close math: texMathZoneV, texMathZoneW, texMathZoneX, texMathZoneY 
    else
	"{{{3 Close math in the current line
	if !return_only
	    if l:begin_line != line(".")
		echomsg "[ATP:] closing math from line " . l:begin_line
	    endif
	endif
	if 
	    \ math_mode == 'texMathZoneV' && ( l:line !~ '^\s*\\(\s*$'	|| line(".") == l:begin_line )	|| 
	    \ math_mode == 'texMathZoneW' && ( l:line !~ '^\s*\\\[\s*$' )				||
	    \ math_mode == 'texMathZoneX' && ( l:line !~ '^\s*\$\s*$' 	|| line(".") == l:begin_line ) 	||
	    \ math_mode == 'texMathZoneY' && ( l:line !~ '^\s*\$\{2,2}\s*$' )
	    if g:atp_debugCloseLastEnvironment
		call atplib#Log('CloseLastEnvironment.log', 'inline math')
	    endif
	    if math_mode == "texMathZoneW"
		if !return_only
		    if l:com == 'a' 
			if getline(l:begin_line) =~ '^\s*\\\[\s*$'
			    call append(line("."),atplib#complete#CopyIndentation(getline(l:begin_line)).'\]')
			else
			    call setline(line("."), strpart(l:cline,0,getpos(".")[2]) . '\]'. strpart(l:cline,getpos(".")[2]))
			endif
		    else
			if getline(l:begin_line) =~ '^\s*\\\[\s*$'
			    call append(line("."),atplib#complete#CopyIndentation(getline(l:begin_line)).'\]')
			else
			    call setline(line("."), strpart(l:cline,0,getpos(".")[2]-1) . '\]'. strpart(l:cline,getpos(".")[2]-1))
    " TODO: This could be optional: (but the option rather
    " should be an argument of this function rather than
    " here!
			endif
			let l:pos=getpos(".")
			let l:pos[2]+=2
			keepjumps call setpos(("."),l:pos)
			let b:cle_return="texMathZoneW"
		    endif
		else
		    let g:time_CloseLastEnvironment = reltimestr(reltime(time))
		    return '\]'
		endif
	    elseif math_mode == "texMathZoneV"
		if !return_only
		    if l:com == 'a'
			call setline(line("."), strpart(l:cline,0,getpos(".")[2]) . '\)'. strpart(l:cline,getpos(".")[2]))
		    else
			call setline(line("."), strpart(l:cline,0,getpos(".")[2]-1) . '\)'. strpart(l:cline,getpos(".")[2]-1))
			call cursor(line("."),col(".")+2)
			let b:cle_return="V"
		    endif
		else
		    let g:time_CloseLastEnvironment = reltimestr(reltime(time))
		    return '\)'
		endif
	    elseif math_mode == "texMathZoneX" 
		if !return_only
		    call setline(line("."), strpart(l:cline,0,getpos(".")[2]-1) . '$'. strpart(l:cline,getpos(".")[2]-1))
		    call cursor(line("."),col(".")+1)
		else
		    let g:time_CloseLastEnvironment = reltimestr(reltime(time))
		    return "$"
		endif
	    elseif math_mode == "texMathZoneY" 
		if !return_only
		    call setline(line("."), strpart(l:cline,0,getpos(".")[2]-1) . '$$'. strpart(l:cline,getpos(".")[2]-1))
		    call cursor(line("."),col(".")+2)
		else
		    let g:time_CloseLastEnvironment = reltimestr(reltime(time))
		    return '$$'
		endif
	    endif " }}}3
	"{{{3 Close math in a new line, preserv the indentation.
	else 	    
	    let l:eindent=atplib#complete#CopyIndentation(l:line)
	    if math_mode == 'texMathZoneW'
		if !return_only
		    let l:iline=line(".")
		    " if the current line is empty append before it.
		    if getline(".") =~ '^\s*$' && l:iline > 1
			let l:iline-=1
		    endif
		    call append(l:iline, l:eindent . '\]')
		    echomsg "[ATP:] \[ closed in line " . l:iline
		else
		    let g:time_CloseLastEnvironment = reltimestr(reltime(time))
		    return '\]'
		endif
    " 		let b:cle_return=2 . " dispalyed math " . l:iline  . " indent " . len(l:eindent) " DEBUG
	    elseif math_mode == 'texMathZoneV'
		if !return_only
		    let l:iline=line(".")
		    " if the current line is empty append before it.
		    if getline(".") =~ '^\s*$' && l:iline > 1
			let l:iline-=1
		    endif
		    call append(l:iline, l:eindent . '\)')
		    echomsg "[ATP:] \( closed in line " . l:iline
		else
		    let g:time_CloseLastEnvironment = reltimestr(reltime(time))
		    return '\)'
		endif
    " 		let b:cle_return=2 . " inline math " . l:iline . " indent " .len(l:eindent) " DEBUG
	    elseif math_mode == 'texMathZoneX'
		if !return_only
		    let l:iline=line(".")
		    " if the current line is empty append before it.
		    if getline(".") =~ '^\s*$' && l:iline > 1
			let l:iline-=1
		    endif
		    let sindent=atplib#complete#CopyIndentation(getline(search('\$', 'bnW')))
		    call append(l:iline, sindent . '$')
		    echomsg "[ATP:] $ closed in line " . l:iline
		else
		    let g:time_CloseLastEnvironment = reltimestr(reltime(time))
		    return '$'
		endif
	    elseif math_mode == 'texMathZoneY'
		if !return_only
		    let l:iline=line(".")
		    " if the current line is empty append before it.
		    if getline(".") =~ '^\s*$' && l:iline > 1
			let l:iline-=1
		    endif
		    let sindent=atplib#complete#CopyIndentation(getline(search('\$\$', 'bnW')))
		    call append(l:iline, sindent . '$$')
		    echomsg "[ATP:] $ closed in line " . l:iline
		else
		    let g:time_CloseLastEnvironment = reltimestr(reltime(time))
		    return '$$'
		endif
	    endif
	endif "}}3
    endif
    if g:atp_debugCloseLastEnvironment
	silent echo "return G"
	redir END
    endif
    "}}}2
    let g:time_CloseLastEnvironment = reltimestr(reltime(time))
    return ''
endfunction
" imap <F7> <Esc>:call atplib#CloseLastEnvironment()<CR>
" }}}1
" {{{1 atplib#complete#CheckBracket
" The first function only tests if there is a bracket to be closed.
" Returns a list [ l:open_line, l:open_col, l:open_bracket ] 
" l:open_col != 0 if any of brackets (in values(g:atp_bracket_dict) ) is
" opened and not closed. l:open_bracket is the most recent such bracket
" ([ l:open_line, l:open_col ] are its coordinates). 
"
" a:bracket_dict is a dictionary of brackets to use: 
" 	 	{ open_bracket : close_bracket } 
"
" Note: the most time consuming part is searchpairpos() function, especially
" for the {:} pair.
" to make it faster I could first count the number of { and } and compare
" them.
try
function! atplib#complete#CheckBracket(bracket_dict)

    let time		= reltime()
    let limit_line	= max([1,(line(".")-g:atp_completion_limits[4])])
    let pos		= getpos(".")
    call search('\S', 'bW')
    let begin_line	= max([search('\%(\\par\>\|^\s*$\)', 'bnW'), limit_line])
    let end_line	= min([search('\%(\\par\>\|^\s*$\)', 'nW'), min([line('$'), line(".")+g:atp_completion_limits[4]])]) 
    call cursor(pos[1:2])
    let length 		= end_line-begin_line


    if g:atp_debugCheckBracket
	let g:begin_line	= begin_line
	let g:end_line		= end_line
	let g:limit_line	= limit_line
	let g:length		= length
    endif
    let pos_saved 	= getpos(".")

    " Bracket sizes:
    let ket_pattern	= '\%(' . join(values(filter(copy(g:atp_sizes_of_brackets), "v:val != '\\'")), '\|') . '\)'


   " But maybe we shouldn't check if the bracket is closed sometimes one can
   " want to close closed bracket and delete the old one.
   
   let check_list = []
   if g:atp_debugCheckBracket
       call atplib#Log("CheckBracket.log","", "init")
       let g:check_list	= check_list
   endif

    "    change the position! and then: 
    "    check the flag 'r' in searchpair!!!

    "Note: this can be much faster to first to check if the line is matching
    " \({\|...<all_brackets>\)[^}...<all brackets>]*, etc., but this would not
    " break which bracket to close.
    let i=0
    let bracket_list= keys(a:bracket_dict)
    for ket in bracket_list
	let pos		= deepcopy(pos_saved)
	let time_{i}	= reltime()
	if ket != '{' && ket != '(' && ket != '['
	    if search('\\\@<!'.escape(ket,'\[]'), 'bnW', begin_line)
		let bslash = ( ket != '{' ? '\\\@<!' : '' )
		if ket != '\begin'
		    let pair_{i}	= searchpairpos(bslash.escape(ket,'\[]').'\zs','', bslash.escape(a:bracket_dict[ket], '\[]'). 
			    \ ( ket_pattern != "" ? '\|'.ket_pattern.'\.' : '' ) , 'bnW', "", begin_line)
		else
		    let pair_{i}	= searchpairpos(bslash.'\zs'.escape(ket,'\[]'),'', bslash.escape(a:bracket_dict[ket], '\[]'). 
			    \ ( ket_pattern != "" ? '\|'.ket_pattern.'\.' : '' ) , 'bnW', "", begin_line)
		endif
	    else
		let pair_{i}	= [0, 0]
	    endif
	else
" 	    This is only for brackets: (:), {:} and [:].

" 	    if search('\\\@<!'.escape(ket,'\[]'), 'bnW', limit_line)
" 	    Without this if ~17s with ~19s (100 times), when this code is used
" 	    also for '[' the time was ~16.5s with '<' : ~17s (this bracket is
" 	    not that common, at the place where I was testing it was not
" 	    appearing)
		let ob=0
		let cb=0
		for lnr in range(begin_line, line("."))
		    if lnr == line(".")
			let line_str=strpart(getline(lnr), 0, pos_saved[2])
		    else
			let line_str=getline(lnr)
		    endif
		    " Remove comments:
		    let line_str	= substitute(line_str, '\(\\\@<!\|\\\@<!\%(\\\\\)*\)\zs%.*$', '', '')
		    " Remove \input[...] and \(:\), \[:\]:
		    let line_str 	= substitute(line_str, '\\input\s*\[[^\]]*\]\|\\\@<!\\\%((\|)\|\[\|\]\)', '', 'g') 
		    let line_list 	= split(line_str, '\zs')

		    let ob+=count(line_list, ket)
		    let cb+=count(line_list, a:bracket_dict[ket])
		endfor
		call cursor(limit_line, 1)
		let first_ket_pos	= searchpos(escape(ket,'\[]').'\|'.escape(a:bracket_dict[ket],'\[]'), 'cW', pos_saved[1])
		call cursor(pos_saved[1], pos_saved[2])
		let first_ket		= ( first_ket_pos[1] ? getline(first_ket_pos[0])[first_ket_pos[1]-1] : '{' )

	        if g:atp_debugCheckBracket
		    call atplib#Log("CheckBracket.log",ket." ob=".ob." cb=".cb." first_ket=".first_ket." cond=".(( ob != cb && first_ket == ket ) || ( ob != cb-1 && first_ket != ket )))
		    call atplib#Log("CheckBracket.log",ket." first_ket_pos=".string(first_ket_pos))
		    call atplib#Log("CheckBracket.log",ket." pos=".string(getpos(".")))
		endif
		if ( ob != cb && first_ket == ket ) || ( ob != cb-1 && first_ket != ket )
		    let bslash = ( ket != '{' ? '\\\@<!' : '' )
		    call atplib#Log("CheckBracket.log",ket." searchpairpos args=".bslash.escape(ket,'\[]')." ".bslash.escape(a:bracket_dict[ket], '\[]'). " begin_line=".begin_line)
		    let pair_{i}	= searchpairpos(bslash.escape(ket,'\[]'),'', bslash.escape(a:bracket_dict[ket], '\[]') , 'bcnW', "", begin_line)
		else
		    let pair_{i}	= [0, 0]
		endif
	endif
	let g:time_A_{i}  = reltimestr(reltime(time_{i}))

	if g:atp_debugCheckBracket >= 2
	    echomsg escape(ket,'\[]') . " pair_".i."=".string(pair_{i}) . " limit_line=" . limit_line
	endif
	if g:atp_debugCheckBracket >= 1
	    call atplib#Log("CheckBracket.log", ket." time_A_".i."=".string(g:time_A_{i}))
	    call atplib#Log("CheckBracket.log", ket." pair_".i."=".string(pair_{i}))
	endif
	let pos[1]	= pair_{i}[0]
	let pos[2]	= pair_{i}[1]

	let no_backslash = ( i == 0 || i == 2 ? '\\\@<!' : '' )
	if i == 3
	    let g:atp_debugCheckClosed = 1
	else
	    let g:atp_debugCheckClosed = 0
	endif
	if pos[1] != 0
" 	    let check_{i} = atplib#complete#CheckClosed(no_backslash.escape(ket,'\[]'),
" 			\ '\%('.no_backslash.escape(a:bracket_dict[ket],'\[]').'\|\\\.\)', 
" 			\ max([0,pos[1]-g:atp_completion_limits[4]]), 1, 2*g:atp_completion_limits[4],2)
	    if  i == 2
		let g:atp_debugCheckClosed = 1
	    endif
	    let check_{i} = atplib#complete#CheckClosed(no_backslash.escape(ket,'\[]'),
			\ '\%('.no_backslash.escape(a:bracket_dict[ket],'\[]').'\|\\\.\)', 
			\ begin_line, 1, length, 2)
	    let g:atp_debugCheckClosed = 0
	    let check_{i} = ( check_{i} == 0 )
	else
	    let check_{i} = 0
	endif

	if g:atp_debugCheckBracket >= 1
	    call atplib#Log("CheckBracket.log", ket." check_".i."=".string(check_{i}))
	    let g:check_{i} = check_{i}
	    let g:arg_{i}=[escape(ket,'\[]'), '\%('.escape(a:bracket_dict[ket],'\[]').'\|\\\.\)', begin_line, 1, 2*g:atp_completion_limits[4],2]
	endif
	" check_dot_{i} is 1 if the bracket is closed with a dot (\right.) . 
" 	let check_dot_{i} = atplib#complete#CheckClosed('\\\@<!'.escape(ket, '\[]'), '\\\.', line("."), pos[1], g:atp_completion_limits[4], 1) == '0'
	let check_dot_{i} = 1
	if g:atp_debugCheckBracket >= 1
	    call atplib#Log("CheckBracket.log", ket." check_dot_".i."=".string(check_{i}))
	endif
	if g:atp_debugCheckBracket >= 2
	    echomsg escape(ket,'\[]') . " check_".i."=".string(check_{i}) . " check_dot_".i."=".string(check_dot_{i})
	endif
	let check_{i}	= min([check_{i}, check_dot_{i}])
	call add(check_list, [ pair_{i}[0], ((check_{i})*pair_{i}[1]), i ] ) 
	keepjumps call setpos(".",pos_saved)
	let g:time_B_{i}  = reltimestr(reltime(time_{i}))
	call atplib#Log("CheckBracket.log", ket." time_B_".i."=".string(g:time_B_{i}))
	let i+=1
    endfor
"     let g:time_CheckBracket_A=reltimestr(reltime(time))
    keepjumps call setpos(".", pos_saved)
   
    " Find opening line and column numbers
    call sort(check_list, "atplib#CompareCoordinates")
    let g:check_list = check_list
    let [ open_line, open_col, open_bracket_nr ] 	= check_list[0]
    let [ s:open_line, s:open_col, s:opening_bracket ] 	= [ open_line, open_col, bracket_list[open_bracket_nr] ]
    if g:atp_debugCheckBracket
	let [ g:open_lineCB, g:open_colCB, g:opening_bracketCB ] = [ open_line, open_col, bracket_list[open_bracket_nr] ]
	call atplib#Log("CheckBracket.log", "return:")
	call atplib#Log("CheckBracket.log", "open_line=".open_line)
	call atplib#Log("CheckBracket.log", "open_col=".open_col)
	call atplib#Log("CheckBracket.log", "opening_bracketCB=".g:opening_bracketCB)
    endif
    let g:time_CheckBracket=reltimestr(reltime(time))
"     let g:time=g:time+str2float(substitute(g:time_CheckBracket, '\.', ',', ''))
    return [ open_line, open_col, bracket_list[open_bracket_nr] ]
endfunction
catch /E127:/
endtry
" }}}1
" {{{1 atplib#complete#CloseLastBracket
"
" The second function closes the bracket if it was not closed. 
" (as returned by atplib#complete#CheckBracket or [ s:open_line, s:open_col, s:opening_bracket ])

" It is not used to close \(:\) and \[:\] as atplib#complete#CloseLastEnvironment has a better
" way of doing that (preserving indentation)
" a:bracket_dict is a dictionary of brackets to use: 
" 	 	{ open_bracket : close_bracket } 
" a:1 = 1 just return the bracket 
" a:2 = 0 (default), 1 when used in atplib#complete#TabCompletion 
" 			then s:open_line, s:open_col and s:opening_bracket are
" 			used to avoid running twice atplib#complete#CheckBracket():
" 			once in atplib#complete#TabCompletion and secondly in CloseLastBracket
" 			function.

function! atplib#complete#CloseLastBracket(bracket_dict, ...)
    
    let only_return	= ( a:0 >= 1 ? a:1 : 0 )
    let tab_completion	= ( a:0 >= 2 ? a:2 : 0 )

    " {{{2 preambule
    let pattern		= ""
    let size_patterns	= []
    for size in keys(g:atp_sizes_of_brackets)
	call add(size_patterns,escape(size,'\'))
    endfor

    let pattern_b	= '\C\%('.join(size_patterns,'\|').'\)'
    let pattern_o	= '\%('.join(map(keys(a:bracket_dict),'escape(v:val,"\\[]")'),'\|').'\)'

    if g:atp_debugCloseLastBracket
	call atplib#Log("CloseLastBracket.log","","init")
	let g:pattern_b	= pattern_b
	let g:pattern_o	= pattern_o
	call atplib#Log("CloseLastBracket.log", "pattern_b=".pattern_b)
	call atplib#Log("CloseLastBracket.log", "pattern_o=".pattern_o)
    endif

    let limit_line	= max([1,(line(".")-g:atp_completion_limits[1])])
        
    let pos_saved 	= getpos(".")


   " But maybe we shouldn't check if the bracket is closed sometimes one can
   " want to close closed bracket and delete the old one.
   
    call cursor(line("."), col(".")-1)
    let [ open_line, open_col, opening_bracket ] = ( tab_completion ? 
		\ deepcopy([ s:open_line, s:open_col, s:opening_bracket ]) : atplib#complete#CheckBracket(a:bracket_dict) )
    call cursor(line("."), pos_saved[2])

    " Check and Close Environment:
    for env_name in g:atp_closebracket_checkenv
	" To Do: this should check for the most recent opened environment
	let limit_line 	= exists("open_line") ? open_line : search('\\\@<!\\\[\|\\\@<!\\(\|\$', 'bn')
	let open_env 	= searchpairpos('\\begin\s*{\s*'.env_name.'\s*}', '', '\\end\s*{\s*'.env_name.'\s*}', 'bnW', '', limit_line)
	let env_name 	= matchstr(strpart(getline(open_env[0]),open_env[1]-1), '\\begin\s*{\s*\zs[^}]*\ze*\s*}')
	if open_env[0] && atplib#CompareCoordinates([(exists("open_line") ? open_line : 0),(exists("open_line") ? open_col : 0)], open_env)
	    call atplib#complete#CloseLastEnvironment('i', 'environment', env_name, open_env)
	    return 'closeing ' . env_name . ' at ' . string(open_env) 
	endif
    endfor

   " Debug:
   if g:atp_debugCloseLastBracket
       let g:open_line	= open_line
       let g:open_col	= open_col 
       call atplib#Log("CloseLastBracket.log", "open_line=".open_line)
       call atplib#Log("CloseLastBracket.log", "open_col=".open_col)
   endif
    "}}}2
    " {{{2 main if statements
   if matchstr(getline(open_line), '...', open_col-3) =~ '\\\@<!\\\%((\|\[\)$'
       call atplib#complete#CloseLastEnvironment('i', 'math', '', [ open_line, open_col ])
       if g:atp_debugCloseLastBracket
	   let b:atp_debugCLB = "call atplib#complete#CloseLastEnvironment('i', 'math', '', [ ".open_line.", ".open_col." ])"
	   call atplib#Log("CloseLastBracket.log", "calling atplib#complete#CloseLastEnvironment('i', 'math', '', [ ".open_line.", ".open_col." ])")
       endif
       return
   endif

   if open_col 
	let line	= getline(open_line)
	let bline	= strpart(line,0,open_col-1)
	if g:atp_debugCloseLastBracket
	    let g:bline = bline
	    call atplib#Log("CloseLastBracket.log", "bline=".bline)
	endif

	let opening_size=matchstr(bline,'\zs'.pattern_b.'\s*\ze$')
	if opening_size =~ '^\\\s\+$'
	    let opening_size = ""
	    let space = ""
	else
	    let matchlist = matchlist(opening_size, '^\(\S*\)\(\s*\)$')
	    let opening_size = matchlist[1]
	    let space	= matchlist[2]
	endif
	let closing_size=get(g:atp_sizes_of_brackets, opening_size, "").space
	" DEBUG
	if g:atp_debugCloseLastBracket
	    call atplib#Log("CloseLastBracket.log", "opening_size=".opening_size)
	    call atplib#Log("CloseLastBracket.log", "closing_size=".closing_size)
	endif
	" Do not add closing size if it is already there.
	if get(g:atp_sizes_of_brackets, opening_size, "") != "" && 
		\ matchstr(getline("."), '^.*\ze\%'.col(".").'c') =~ escape(get(g:atp_sizes_of_brackets, opening_size, ""), '\').'\s*$' 
	    let closing_size=""
	endif

	if opening_size == "\\" && opening_bracket != '(' && opening_bracket != '['
	    " This is done for \right\}
	    let bbline		= strpart(bline, 0, len(bline)-1)
	    let opening_size2	= matchstr(bbline,'\zs'.pattern_b.'\s*$')
	    if opening_size2 =~ '^\\\s\+$'
		let opening_size2 = ""
		let space2 = ""
	    else
		let matchlist2 = matchlist(opening_size2, '^\(\S*\)\(\s*\)$')
		let opening_size2 = matchlist2[1]
		let space2	= matchlist2[2]
	    endif
	    let closing_size2	= get(g:atp_sizes_of_brackets,opening_size2,"")
	    let closing_size	= closing_size2.space2.closing_size
	    " Do not add closing size if it is already there.
	    if get(g:atp_sizes_of_brackets,opening_size2,"") != "" && 
		    \ matchstr(getline("."), '^.*\ze\%'.col(".").'c') =~ escape(get(g:atp_sizes_of_brackets,opening_size2,""), '\').'\s*$'
		let closing_size=get(g:atp_sizes_of_brackets,opening_size,"")
	    endif

	    " DEBUG
	    if g:atp_debugCloseLastBracket
		let g:bbline		= bbline
		let g:opening_size2	= opening_size2
		let g:closing_size2	= closing_size2
		call atplib#Log("CloseLastBracket.log", "bbline=".bbline)
		call atplib#Log("CloseLastBracket.log", "opening_size2=".opening_size2)
		call atplib#Log("CloseLastBracket.log", "closing_size2=".closing_size2)
	    endif
	endif
" 	if cline[1:col(".")-1] =~ g:atp

	if open_line != line(".")
	    echomsg "[ATP:] closing " . opening_size . opening_bracket . " from line " . open_line
	endif

	" DEBUG:
	if g:atp_debugCloseLastBracket
	    call atplib#Log("CloseLastBracket.log", "======")
	    let g:o_bra		= opening_bracket
	    call atplib#Log("CloseLastBracket.log", "opening_bracket=".opening_bracket)
	    let g:o_size	= opening_size
	    call atplib#Log("CloseLastBracket.log", "opening_size=".opening_size)
	    let g:bline		= bline
	    call atplib#Log("CloseLastBracket.log", "bline=".bline)
	    let g:line		= line
	    call atplib#Log("CloseLastBracket.log", "line=".line)
	    let g:opening_size	= opening_size
	    call atplib#Log("CloseLastBracket.log", "opening_size=".opening_size)
	    let g:closing_size	= closing_size
	    call atplib#Log("CloseLastBracket.log", "closing_size=".closing_size)
	endif

	let cline=getline(line("."))
	if mode() == 'i'
	    if !only_return
		call setline(line("."), strpart(cline, 0, getpos(".")[2]-1).
			\ closing_size.get(a:bracket_dict, opening_bracket). 
			\ strpart(cline,getpos(".")[2]-1))
	    endif
	    let l:return=closing_size.get(a:bracket_dict, opening_bracket)
	elseif mode() == 'n'
	    if !only_return
		call setline(line("."), strpart(cline,0,getpos(".")[2]).
			\ closing_size.get(a:bracket_dict,opening_bracket). 
			\ strpart(cline,getpos(".")[2]))
	    endif
	    let l:return=closing_size.get(a:bracket_dict, opening_bracket)
	endif
	let pos=getpos(".")
	let pos[2]+=len(closing_size.get(a:bracket_dict, opening_bracket))
	keepjumps call setpos(".", pos)

	return l:return
   endif
   " }}}2
endfunction
" }}}1
" {{{1 atplib#complete#GetBracket
" This function is used in atplib#complete#TabCompletion in several places.
" It combines both above atplib#complete#CloseLastEnvironment and
" atplib#complete#CloseLastBracket functions.
try
function! atplib#complete#GetBracket(append,bracket_dict,...)
    " a:1 = 0  - pass through first if (it might be checked already).
    " a:2 = atplib#complete#CheckBracket(g:atp_bracket_dict)
    " a:3 = starting position (used be omnicompletion)
    let time=reltime()
"     if a:0 >= 3
" 	let saved_pos=getpos(".")
" 	let pos = a:3
" 	call setpos(".", a:3)
"     else
	let pos = getpos(".")
" 	let saved_pos = getpos(".")
"     endif
"     let g:pos = copy(pos)
"     let g:apos = getpos(".")
"     call cursor(pos[1], pos[2]-1)
"     let g:bpos = copy(getpos("."))
    let begParen = ( a:0 >=2 && a:2 != [] ? a:2 : atplib#complete#CheckBracket(a:bracket_dict) )
    let g:begParen = copy(begParen)
    if begParen[2] == '\begin' && begParen[1] && !atplib#complete#CheckSyntaxGroups(['texMathZoneX', 'texMathZoneY', 'texMathZoneV', 'texMathZoneW'])
	call atplib#complete#CloseLastEnvironment(a:append, 'environment', matchstr(getline(begParen[0]), '.*\\begin{\s*\zs[^}]*\ze\s*}'), [begParen[0], begParen[1]-6])
	return ''
    endif

    call cursor(pos[1], pos[2])
    if begParen[1] != 0  || atplib#complete#CheckSyntaxGroups(['texMathZoneX', 'texMathZoneY', 'texMathZoneV', 'texMathZoneW']) || ( a:0 >= 1 && a:1 )
	let g:cpos = getpos(".")
	if atplib#complete#CheckSyntaxGroups(['texMathZoneV'])
	    let pattern = '\\\@<!\\\zs('
	    let syntax	= 'texMathZoneV'
	    let limit	= g:atp_completion_limits[0]
	elseif atplib#complete#CheckSyntaxGroups(['texMathZoneW'])
	    let pattern = '\\\@<!\\\zs\['
	    let syntax	= 'texMathZoneW'
	    let limit	= g:atp_completion_limits[1]
	elseif atplib#complete#CheckSyntaxGroups(['texMathZoneX'])
	    let pattern = '\%(\\\|\$\)\@<!\zs\$\$\@!'
	    let syntax	= 'texMathZoneX'
	    let limit	= g:atp_completion_limits[0]
	elseif atplib#complete#CheckSyntaxGroups(['texMathZoneY'])
	    let pattern = '\\\@<!\$\zs\$'
	    let syntax	= 'texMathZoneY'
	    let limit	= g:atp_completion_limits[1]
	else
	    let pattern = ''
	endif
	let g:pattern = pattern

	if !empty(pattern)
	    let begMathZone = searchpos(pattern, 'bnW')
	    let g:begMathZone = copy(begMathZone)
	    let g:begParen	= copy(begParen)
	    let closed_math	= atplib#complete#CheckClosed_math(syntax)
	    if atplib#CompareCoordinates([ begParen[0], begParen[1] ], begMathZone) && closed_math
		" I should close it if math is not closed.
		let bracket = atplib#complete#CloseLastEnvironment(a:append, 'math', '', [0, 0], 1)
	    elseif (begParen[0] != 0 && begParen[1] !=0) && atplib#complete#CheckSyntaxGroups(['texMathZoneV', 'texMathZoneW', 'texMathZoneX', 'texMathZoneY'], begParen[0], begParen[1]) == atplib#complete#CheckSyntaxGroups(['texMathZoneV', 'texMathZoneW', 'texMathZoneX', 'texMathZoneY'], line("."), max([1,col(".")-1]))
		let [s:open_line, s:open_col, s:opening_bracket]=begParen
		let bracket = atplib#complete#CloseLastBracket(a:bracket_dict, 1, 1)
	    else
		let bracket = "0"
	    endif
	else
	    let bracket =  atplib#complete#CloseLastBracket(a:bracket_dict, 1, 1)
	endif
	call setpos(".", pos)
" 	call setpos(".", saved_pos)
	let g:time_GetBrackets=reltimestr(reltime(time))
	if bracket != "0"
	    return bracket
	else
	    return ''
	endif
    endif
    let g:time_GetBrackets=reltimestr(reltime(time))
    return ''
endfunction
catch /E127:/
endtry
"}}}1


" Completions:
" atplib#complete#TabCompletion {{{1
" This is the main TAB COMPLITION function.
"
" expert_mode = 1 (on)  gives less completions in some cases (commands,...)
" 			the matching pattern has to match at the beginning and
" 			is case sensitive. Furthermode  in expert mode, if
" 			completing a command and found less than 1 match then
" 			the function tries to close \(:\) or \[:\] (but not an
" 			environment, before doing ToDo in line 3832 there is
" 			no sense to make it).
" 			<Tab> or <F7> (if g:atp_no_tab_map=1)
" expert_mode = 0 (off) gives more matches but in some cases better ones, the
" 			string has to match somewhare and is case in
" 			sensitive, for example:
" 			\arrow<Tab> will show all the arrows definded in tex,
" 			in expert mode there would be no match (as there is no
" 			command in tex which begins with \arrow).
" 			<S-Tab> or <S-F7> (if g:atp_no_tab_map=1)
"
" Completion Modes: (this is not a complete list any more, see the
" documentation of ATP)
" 	documentclass (\documentclass)
" 	labels   (\ref,\eqref)
" 	packages (\usepackage)
" 	commands
" 	environments (\begin,\(:\),\[:\])
" 	brackets ((:),[:],{:}) preserves the size operators!
" 		Always: check first brackets then environments. Bracket
" 		funnction can call function which closes environemnts but not
" 		vice versa.
" 	bibitems (\cite\|\citep\|citet)
" 	bibfiles (\bibliography)
" 	bibstyle (\bibliographystyle)
" 	end	 (close \begin{env} with \end{env})
" 	font encoding
" 	font family
" 	font series
" 	font shape
" 
"ToDo: the completion should be only done if the completed text is different
"from what it is. But it might be as it is, there are reasons to keep this.
"
try
" Main tab completion function
function! atplib#complete#TabCompletion(expert_mode,...)

    if g:atp_debugTabCompletion
	call atplib#Log("TabCompletion.log", "", "init")
    endif

    let time=reltime()
    let atp_MainFile	= atplib#FullPath(b:atp_MainFile)
    " {{{2 Match the completed word 
    let normal_mode=0

    if a:0 >= 1
	let normal_mode=a:1
    endif

    " this specifies the default argument for atplib#complete#CloseLastEnvironment()
    " in some cases it is better to append after than before.
    let append='i'

    " Define string parts used in various completitons
    let pos		= getpos(".")
    let pos_saved	= deepcopy(pos)
    let line		= join(getbufline("%",pos[1]))
    let nchar		= strpart(line,pos[2]-1,1)
"     let rest		= strpart(line,pos[2]-1) 
    let l		= strpart(line,0,pos[2]-1)
    let n		= strridx(l,'{')
    let m		= strridx(l,',')
    let o		= strridx(l,'\')
    let s		= strridx(l,' ')
    let p		= strridx(l,'[')
    let r		= strridx(l,'=')
    let c		= match(l, '\\cite\>\(.*\\cite\>\)\@!') 
    let a		= len(l) - stridx(join(reverse(split(l, '\zs')), ''), "=")
     
    let nr=max([n,m,o,s,p])
    let color_nr=max([nr, r])

    " this matches for =...
    let abegin		= strpart(l, a-1)

    " this matches for \...
    let begin		= strpart(l,nr+1)
    let cmd_val_begin	= strpart(l,max([nr+1,r+1]))
    let color_begin	= strpart(l,color_nr+1)
    let cbegin		= strpart(l,nr)
    " and this for '\<\w*$' (beginning of last started word) -- used in
    " tikzpicture completion method 
    let tbegin		= matchstr(l,'\zs\<\w*$')
    " start with last '\'
    let obegin		= strpart(l,o)
    " start with last =
    let ebegin		= strpart(l,max([r,m,n])+1)

    " what we are trying to complete: usepackage, environment.
    let pline		= strpart(l, 0, nr)
    	" \cite[Theorem~1]{Abcd -> \cite[Theorem~] 
    let ppline		= strpart(l, c)
    	" \cite[Theorem~1]{Abcd -> \cite[Theorem~1]{ 

    let limit_line=max([1,(pos[1]-g:atp_completion_limits[1])])

    if g:atp_debugTabCompletion
	let g:nchar	= nchar
	call atplib#Log("TabCompletion.log", "nchar=".nchar)
	let g:l		= l
	call atplib#Log("TabCompletion.log", "l=".l)
	let g:n		= n
	call atplib#Log("TabCompletion.log", "n=".n)
	let g:o		= o
	call atplib#Log("TabCompletion.log", "o=".o)
	let g:s		= s
	call atplib#Log("TabCompletion.log", "s=".s)
	let g:p		= p
	call atplib#Log("TabCompletion.log", "p=".p)
	let g:a		= a
	call atplib#Log("TabCompletion.log", "a=".a)
	let g:nr	= nr
	call atplib#Log("TabCompletion.log", "nr=".nr)

	let g:line	= line    
	call atplib#Log("TabCompletion.log", "line=".line)
	let g:abegin	= abegin
	call atplib#Log("TabCompletion.log", "abegin=".abegin)
	let g:cmd_val_begin = cmd_val_begin
	call atplib#Log("TabCompletion.log", "cmd_val_begin=".cmd_val_begin)
	let g:tbegin	= tbegin
	call atplib#Log("TabCompletion.log", "tbegin=".tbegin)
	let g:cbegin	= cbegin
	call atplib#Log("TabCompletion.log", "cbegin=".cbegin)
	let g:obegin	= obegin
	call atplib#Log("TabCompletion.log", "obegin=".obegin)
	let g:begin	= begin 
	call atplib#Log("TabCompletion.log", "begin=".begin)
	let g:ebegin	= ebegin 
	call atplib#Log("TabCompletion.log", "ebegin=".ebegin)
	let g:pline	= pline
	call atplib#Log("TabCompletion.log", "pline=".pline)
	let g:ppline	= ppline
	call atplib#Log("TabCompletion.log", "ppline=".ppline)
	let g:color_begin	= color_begin
	call atplib#Log("TabCompletion.log", "color_begin=".color_begin)

	let g:limit_line= limit_line
	call atplib#Log("TabCompletion.log", "limit_line=".limit_line)
    endif


" {{{2 SET COMPLETION METHOD
    " {{{3 --------- command
    if o > n && o > s && 
	\ pline !~ '\%(input\s*{[^}]*$\|include\%(only\)\=\s*{[^}]*$\|[^\\]\\\\[^\\]$\)' &&
	\ pline !~ '\\\@<!\\$' &&
	\ begin !~ '{\|}\|,\|-\|\^\|\$\|(\|)\|&\|-\|+\|=\|#\|:\|;\|\.\|,\||\|?$' &&
	\ begin !~ '^\[\|\]\|-\|{\|}\|(\|)' &&
	\ cbegin =~ '^\\' && !normal_mode &&
	\ l !~ '\\\%(no\)\?cite[^}]*$' &&
	\ l !~ '\\ref\s*{\S*$' &&
	\ index(g:atp_completion_active_modes, 'commands') != -1
	" in this case we are completing a command
	" the last match are the things which for sure do not ends any
	" command. The pattern '[^\\]\\\\[^\\]$' do not matches "\" and "\\\",
	" in which case the line contains "\\" and "\\\\" ( = line ends!)
	" (here "\" is one character \ not like in magic patterns '\\')
	" but matches "" and "\\" (i.e. when completing "\" or "\\\" [end line
	" + command].
	    let completion_method='command'
	    " DEBUG:
	    let b:comp_method='command'
	    call atplib#Log("TabCompletion.log", "b:comp_method=".b:comp_method)
    "{{{3 --------- environment options
    elseif (l =~ '\\begin\s*{[^}]*}\s*\[[^\]]*$' && !normal_mode) &&
		\ index(g:atp_completion_active_modes, 'environment options') != -1 
	    let completion_method='environment options'
	    " DEBUG:
	    let b:comp_method='environment options'
	    call atplib#Log("TabCompletion.log", "b:comp_method=".b:comp_method)
    "{{{3 --------- environment names
    elseif (pline =~ '\%(\\begin\|\\end\)\s*$' && begin !~ '}.*$' && !normal_mode) &&
		\ index(g:atp_completion_active_modes, 'environment names') != -1 
	    let completion_method='environment_names'
	    " DEBUG:
	    let b:comp_method='environment_names'
	    call atplib#Log("TabCompletion.log", "b:comp_method=".b:comp_method)
    "{{{3 --------- labels
    elseif l =~ '\\\%(eq\|page\|auto\|autopage\)\?ref\*\={[^}]*$\|\\hyperref\s*\[[^\]]*$' && !normal_mode &&
		\ index(g:atp_completion_active_modes, 'labels') != -1 
	    let completion_method='labels'
	    " DEBUG:
	    let b:comp_method='labels'
	    call atplib#Log("TabCompletion.log", "b:comp_method=".b:comp_method)
    "{{{3 --------- pagestyle
    elseif l =~ '\\\%(pagestyle\|thispagestyle\){[^}]*$' &&
		\ index(g:atp_completion_active_modes, 'page styles') != -1 
	let completion_method='pagestyle'
	" DEBUG:
	let b:comp_method='pagestyle'
	call atplib#Log("TabCompletion.log", "b:comp_method=".b:comp_method)
    "{{{3 --------- pagenumbering
    elseif l =~ '\\pagenumbering{[^}]*$' &&
		\ index(g:atp_completion_active_modes, 'page numberings') != -1 
	let completion_method='pagenumbering'
	" DEBUG:
	let b:comp_method='pagenumbering'
	call atplib#Log("TabCompletion.log", "b:comp_method=".b:comp_method)
    "{{{3 --------- bibitems
    elseif ppline =~ '\\\%(no\)\?[cC]ite\%(\%(al\)\?[tp]\*\?\|text\|num\|author\*\?\|year\%(par\)\?\)\?\(\s*\[[^]]*\]\s*\)\={[^}]*$' && !normal_mode &&
		\ index(g:atp_completion_active_modes, 'bibitems') != -1
	    let completion_method='bibitems'
	    " DEBUG:
	    let b:comp_method='bibitems'
	    call atplib#Log("TabCompletion.log", "b:comp_method=".b:comp_method)
    "{{{3 --------- tikzpicture
    elseif 
	\ !normal_mode &&
	\ ( search('\%(\\def\>.*\|\\\%(re\)\?newcommand\>.*\|%.*\)\@<!\\begin{tikzpicture}','bnW') > search('[^%]*\\end{tikzpicture}','bnW') ||
	\ !atplib#CompareCoordinates(searchpos('[^%]*\zs\\tikz{','bnw'),searchpos('}','bnw')) )
	"{{{4 ----------- tikzpicture colors
	if begin =~ '^color='
	    " This is for tikz picture color completion.
	    let completion_method='tikzpicture colors'
	    let b:comp_method='tikzpicture colors'
	    call atplib#Log("TabCompletion.log", "b:comp_method=".b:comp_method)
	"{{{4 ----------- tikzpicture keywords
	elseif l =~ '\%(\s\|\[\|{\|}\|,\|\.\|=\|:\)' . tbegin . '$' &&
		    \ !a:expert_mode
		let b:comp_method='tikzpicture keywords'
		call atplib#Log("TabCompletion.log", "b:comp_method=".b:comp_method)
		let completion_method="tikzpicture keywords"
	"{{{4 ----------- brackets
	else
	    let begParen = atplib#complete#CheckBracket(g:atp_bracket_dict)
	    let g:begParen = begParen
	    if begParen[2] != '\begin' && ( begParen[1] != 0 || atplib#complete#CheckSyntaxGroups(['texMathZoneX', 'texMathZoneY']) &&
		    \ (!normal_mode &&  index(g:atp_completion_active_modes, 'brackets') != -1 ) ||
		    \ (normal_mode && index(g:atp_completion_active_modes_normal_mode, 'brackets') != -1 ) )

		let b:comp_method='brackets tikzpicture'
		let completion_method = 'brackets'
		let bracket=atplib#complete#GetBracket(append, g:atp_bracket_dict, 0, begParen)
		let g:time_TabCompletion=reltimestr(reltime(time))
		let move = ( !a:expert_mode ? join(map(range(len(bracket)), '"\<Left>"'), '') : '' )
		return bracket.move
	"{{{4 ----------- close environments
	    elseif (!normal_mode &&  index(g:atp_completion_active_modes, 'close environments') != '-1' ) ||
			\ (normal_mode && index(g:atp_completion_active_modes_normal_mode, 'close environments') != '-1' )
		let completion_method='close_env'
		" DEBUG:
		let b:comp_method='close_env tikzpicture' 
		call atplib#Log("TabCompletion.log", "b:comp_method=".b:comp_method)
	    else
		return ''
	    endif
	endif
    "{{{3 --------- package options values
    elseif l =~ '\\usepackage\[[^\]]*=\%([^\],]*\|{\([^}]\+,\)\?[^}]*\)$' &&
		\ !( l =~ '\\usepackage\[[^\]]*=\%(.*\]\|{.*}\),$' ) && 
		\ !normal_mode &&
		\  index(g:atp_completion_active_modes, 'package options values') != -1
	    let completion_method='package options values'
	    let b:comp_method=completion_method
    "{{{3 --------- package options
    elseif l =~ '\\usepackage\[[^\]]*$' && !normal_mode &&
		\  index(g:atp_completion_active_modes, 'package options') != -1
	    let completion_method='package options'
	    let b:comp_method=completion_method
    "{{{3 --------- package
    elseif pline =~ '\\usepackage\%([.*]\)\?\s*' && !normal_mode &&
		\  index(g:atp_completion_active_modes, 'package names') != -1
	    let completion_method='package'
	    " DEBUG:
	    let b:comp_method='package'
	    call atplib#Log("TabCompletion.log", "b:comp_method=".b:comp_method)
    "{{{3 --------- tikz libraries
    elseif pline =~ '\\usetikzlibrary\%([.*]\)\?\s*' && !normal_mode &&
		\ index(g:atp_completion_active_modes, 'tikz libraries') != -1
	    let completion_method='tikz libraries'
	    " DEBUG:
	    let b:comp_method='tikz libraries'
	    call atplib#Log("TabCompletion.log", "b:comp_method=".b:comp_method)
    "{{{3 --------- inputfiles
    elseif (l =~ '\\input\%([^{}]*\|\s*{[^}]*\)$'||
	  \ l =~ '\\include\s*{[^}]*$') && !normal_mode &&
	  \ index(g:atp_completion_active_modes, 'input files') != -1
	    if begin =~ 'input'
		let begin=substitute(begin,'.*\%(input\|include\%(only\)\?\)\s\?','','')
	    endif
	    let completion_method='inputfiles'
	    " DEBUG:
	    let b:comp_method='inputfiles'
	    call atplib#Log("TabCompletion.log", "b:comp_method=".b:comp_method)
    "{{{3 --------- includegraphics
    elseif (l =~ '\\includegraphics\s*\(\[[^\]]*\]\s*\)\?{[^}]*$') &&
		\ index(g:atp_completion_active_modes, 'includegraphics') != -1
	    let completion_method='includegraphics'
	    " DEBUG:
	    let b:comp_method='includegraphics'
	    call atplib#Log("TabCompletion.log", "b:comp_method=".b:comp_method)
    "{{{3 --------- bibfiles
    elseif pline =~ '\\\%(bibliography\%(style\)\@!\|addbibresource\|addglobalbib\)' && !normal_mode &&
		\ index(g:atp_completion_active_modes, 'bibfiles') != -1
	    let completion_method='bibfiles'
	    " DEBUG:
	    let b:comp_method='bibfiles'
	    call atplib#Log("TabCompletion.log", "b:comp_method=".b:comp_method)
    "{{{3 --------- bibstyles
    elseif pline =~ '\\bibliographystyle' && !normal_mode  &&
	 \ index(g:atp_completion_active_modes, 'bibstyles') != -1
	    let completion_method='bibstyles'
	    let b:comp_method='bibstyles'
	    call atplib#Log("TabCompletion.log", "b:comp_method=".b:comp_method)
    "{{{3 --------- todo & missingfigure options
    elseif obegin =~ '\\todo\[[^\]]*$' &&
		\ ( index(g:atp_completion_active_modes, 'todonotes') != -1 ) 
	    let completion_method='todo options'
	    let b:comp_method='todo options'
	    call atplib#Log("TabCompletion.log", "b:comp_method=".b:comp_method)
    elseif obegin =~ '\\missingfigure\[[^\]]*$' &&
		\ ( index(g:atp_completion_active_modes, 'todonotes') != -1 )
	    let completion_method='missingfigure options'
	    let b:comp_method='missingfigure options'
	    call atplib#Log("TabCompletion.log", "b:comp_method=".b:comp_method)

    "{{{3 --------- documentclass options
    elseif l =~ '\\documentclass\s*\[[^\]]*$' && !normal_mode  &&
	    \ index(g:atp_completion_active_modes, 'documentclass options') != -1
	    let completion_method='documentclass options'
	    let b:comp_method=completion_method
	    call atplib#Log("TabCompletion.log", "b:comp_method=".b:comp_method)
    "{{{3 --------- documentclass
    elseif pline =~ '\\documentclass\>' && !normal_mode  &&
		\ index(g:atp_completion_active_modes, 'documentclass') != -1
	    let completion_method='documentclass'
	    let b:comp_method='documentclass'
	    call atplib#Log("TabCompletion.log", "b:comp_method=".b:comp_method)
	    call atplib#Log("TabCompletion.log", "b:comp_method=".b:comp_method)
    "{{{3 --------- font family
    elseif l =~ '\%(\\renewcommand\s*{\s*\\\%(rm\|sf\|bf\|tt\|md\|it\|sl\|sc\|up\)default\s*}\s*{\|\\usefont{[^}]*}{\|\\DeclareFixedFont{[^}]*}{[^}]*}{\|\\fontfamily{\)[^}]*$' && !normal_mode  &&
		\ index(g:atp_completion_active_modes, 'font family') != -1
	    let completion_method='font family'
	    let b:comp_method='font family'
	    call atplib#Log("TabCompletion.log", "b:comp_method=".b:comp_method)
    "{{{3 --------- font series
    elseif l =~ '\%(\\usefont{[^}]*}{[^}]*}{\|\\DeclareFixedFont{[^}]*}{[^}]*}{[^}]*}{\|\\fontseries{\)[^}]*$' && 
		\ !normal_mode  &&
		\ index(g:atp_completion_active_modes, 'font series') != -1
	    let completion_method='font series'
	    let b:comp_method='font series'
	    call atplib#Log("TabCompletion.log", "b:comp_method=".b:comp_method)
    "{{{3 --------- font shape
    elseif l =~ '\%(\\usefont{[^}]*}{[^}]*}{[^}]*}{\|\\DeclareFixedFont{[^}]*}{[^}]*}{[^}]*}{[^}]*}{\|\\fontshape{\)[^}]*$' 
		\ && !normal_mode  &&
		\ index(g:atp_completion_active_modes, 'font shape') != -1
	    let completion_method='font shape'
	    let b:comp_method='font shape'
	    call atplib#Log("TabCompletion.log", "b:comp_method=".b:comp_method)
    "{{{3 --------- font encoding
    elseif l =~ '\%(\\usefont{\|\\DeclareFixedFont{[^}]*}{\|\\fontencoding{\)[^}]*$' && !normal_mode  &&
		\ index(g:atp_completion_active_modes, 'font encoding') != -1
	    let completion_method='font encoding'
	    let b:comp_method='font encoding'
	    call atplib#Log("TabCompletion.log", "b:comp_method=".b:comp_method)
    "{{{3 --------- command values
    " this is at the end because there are many command completions done
    " before - they would not work if this would be on the top.
    elseif (l =~ '\%(\\\w\+\%(\[\%([^\]]\|\[[^\]]*\]\)*\]\)\?\%({\%([^}]\|{\%([^}]\|{[^}]*}\)*}\)*}\)\?{\%([^}]\|{\%([^}]\|{[^}]*}\)*}\)*$\|\\renewcommand{[^}]*}{[^}]*$\)' && !normal_mode) &&
		\ index(g:atp_completion_active_modes, 'environment names') != -1 
	    let completion_method="command values"
	    " DEBUG:
	    let b:comp_method=completion_method
	    call atplib#Log("TabCompletion.log", "b:comp_method=".b:comp_method)
    "{{{3 --------- brackets, algorithmic, abbreviations, close environments
    else
	let begParen = atplib#complete#CheckBracket(g:atp_bracket_dict)
	"{{{4 --------- abbreviations
	if l =~ '=[a-zA-Z]\+\*\=$' &&
		\ index(g:atp_completion_active_modes, 'abbreviations') != -1 &&
		\ !atplib#IsInMath() 
	    let completion_method='abbreviations' 
	    let b:comp_method='abbreviations'
	    call atplib#Log("TabCompletion.log", "b:comp_method=".b:comp_method)
	"{{{4 --------- brackets
	elseif begParen[2] != '\begin' && ( begParen[1] != 0 || atplib#complete#CheckSyntaxGroups(['texMathZoneX', 'texMathZoneY']) &&
		\ (!normal_mode &&  index(g:atp_completion_active_modes, 'brackets') != -1 ) ||
		\ (normal_mode && index(g:atp_completion_active_modes_normal_mode, 'brackets') != -1 ) )
	    let completion_method = 'brackets'
	    let b:comp_method='brackets'
	    let bracket=atplib#complete#GetBracket(append, g:atp_bracket_dict, 0, begParen)
	    let g:time_TabCompletion=reltimestr(reltime(time))
	    let move = ( !a:expert_mode ? join(map(range(len(bracket)), '"\<Left>"'), '') : '' )
	    return bracket.move
	"{{{4 --------- close environments
	elseif (!normal_mode &&  index(g:atp_completion_active_modes, 'close environments') != '-1' ) ||
		    \ (normal_mode && index(g:atp_completion_active_modes_normal_mode, 'close environments') != '-1' )
	    let completion_method='close_env X'
	    " DEBUG:
	    let b:comp_method='close_env' 
	    call atplib#Log("TabCompletion.log", "b:comp_method=".b:comp_method)
	"{{{4 --------- algorithmic
	elseif atplib#complete#CheckBracket(g:atp_algorithmic_dict)[0] != 0 && 
		    \ atplib#complete#CheckSyntaxGroups(['texMathZoneALG']) && 
		    \ ((!normal_mode && index(g:atp_completion_active_modes, 'algorithmic' ) != -1 ) ||
		    \ (normal_mode && index(g:atp_completion_active_modes_normal_mode, 'algorithmic') != -1 ))
		let b:comp_method='algorithmic'
		call atplib#Log("TabCompletion.log", "b:comp_method=".b:comp_method)
		call atplib#complete#CloseLastBracket(g:atp_algorithmic_dict, 0, 1)
		let g:time_TabCompletion=reltimestr(reltime(time))
		return '' 
	"}}}4
	else
	    let g:time_TabCompletion=reltimestr(reltime(time))
	    return ''
	endif
	"}}}3
    endif
    let b:completion_method = ( exists("completion_method") ? completion_method : 'completion_method does not exists' )
"}}}2
" {{{2 close environments
    if completion_method=='close_env'

" 	let g:time_A=reltimestr(reltime(time))

	" Close one line math
	if atplib#complete#CheckClosed_math('texMathZoneV') || 
		\ atplib#complete#CheckClosed_math('texMathZoneW') ||
		\ atplib#complete#CheckClosed_math('texMathZoneX') ||
		\ b:atp_TexFlavor == 'plaintex' && atplib#complete#CheckClosed_math('texMathZoneY')
	    let b:tc_return = "close_env math"
	    call atplib#complete#CloseLastEnvironment(append, 'math')
	" Close environments
	else
	    let b:tc_return = "close_env environment"
	    let stopline_forward	= line(".") + g:atp_completion_limits[2]
	    let stopline_backward	= max([ 1, line(".") - g:atp_completion_limits[2]])

	    let line_nr=line(".")
	    let pos_saved=getpos(".")
	    while line_nr >= stopline_backward
		let [ line_nr, col_nr ] = searchpairpos('\\begin\s*{', '', '\\end\s*{', 'bW', 'strpart(getline("."), 0, col(".")-1) =~ "\\\\\\@<!%"', stopline_backward)
		if line_nr >= stopline_backward
		    let env_name	= matchstr(strpart(getline(line_nr), col_nr-1), '\\begin\s*{\zs[^}]*\ze}')
		    if env_name		=~# '^\s*document\s*$' 
			break
		    endif
		    let line_forward 	= searchpair('\\begin\s*{'.env_name.'}', '', '\\end\s*{'.env_name.'}', 
							\ 'nW', '', stopline_forward)
		    if line_forward == 0
			break
		    endif
		else
		    let line_nr = 0
		    break
		endif
	    endwhile
	    call cursor(pos_saved[1], pos_saved[2])

	    if line_nr
	    " the env_name variable might have wrong value as it is
	    " looking using '\\begin' and '\\end' this might be not enough, 
		" however the function atplib#CloseLastEnv works perfectly and this
		" should be save:

		let g:time_TabCompletion=reltimestr(reltime(time))
		if env_name !~# '^\s*document\s*$'
		    call atplib#complete#CloseLastEnvironment(append, 'environment', '', [line_nr, 0])
		    return ""
		else
		    return ""
		endif
	    endif
	endif
	let g:time_TabCompletion=reltimestr(reltime(time))
	return ""
    endif
" {{{2 SET COMPLETION LIST
    " generate the completion names
    " {{{3 ------------ ENVIRONMENT NAMES
    if completion_method == 'environment_names'
	let end=strpart(line,pos[2]-1)

	keepjumps call setpos(".",[0,1,1,0])
	let stop_line=search('\\begin\s*{document}','cnW')
	keepjumps call setpos(".",pos_saved)

	if end !~ '\s*}'
	    let completion_list = []
" 	    if atplib#search#DocumentClass(b:atp_MainFile) == 'beamer'
" 		call extend(completion_list, g:atp_BeamerEnvironments)
" 	    endif
	    call extend(completion_list,deepcopy(g:atp_Environments))
	    if g:atp_local_completion
		" Make a list of local envs and commands
		if !exists("s:atp_LocalEnvironments") 
		    LocalCommands
		    let s:atp_LocalEnvironments=copy(b:atp_LocalEnvironments)
		elseif has("python")
		    LocalCommands
		    let s:atp_LocalEnvironments=copy(b:atp_LocalEnvironments)
		endif
		let completion_list=atplib#Extend(completion_list,s:atp_LocalEnvironments)
	    endif
	    let completion_list=atplib#Add(completion_list,'}')
	else
	    let completion_list = []
" 	    if atplib#search#DocumentClass(b:atp_MainFile) == 'beamer'
" 		call extend(completion_list, g:atp_BeamerEnvironments)
" 	    endif
	    call extend(completion_list,deepcopy(g:atp_Environments))
	    if g:atp_local_completion
		" Make a list of local envs and commands
		if !exists("s:atp_LocalEnvironments") 
		    LocalCommands
		    let s:atp_LocalEnvironments=copy(b:atp_LocalEnvironments)
		elseif has("python")
		    LocalCommands
		    let s:atp_LocalEnvironments=copy(b:atp_LocalEnvironments)
		endif
		call atplib#Extend(completion_list,s:atp_LocalEnvironments)
	    endif
	endif
	" TIKZ
	let in_tikz=searchpair('\\begin\s*{tikzpicture}','','\\end\s*{tikzpicture}','bnW',"", max([1,(line(".")-g:atp_completion_limits[2])])) || atplib#complete#CheckOpened('\\tikz{','}',line("."),g:atp_completion_limits[0])
	if in_tikz
	    if end !~ '\s*}'
		call extend(completion_list,atplib#Add(g:atp_tikz_environments,'}'))
	    else
		call extend(completion_list,g:atp_tikz_environments)
	    endif
	endif
	" AMSMATH
	if atplib#search#SearchPackage('amsmath', stop_line) || g:atp_amsmath != 0 || atplib#search#DocumentClass(b:atp_MainFile) =~ '^ams'
	    if end !~ '\s*}'
		call extend(completion_list,atplib#Add(g:atp_amsmath_environments,'}'),0)
	    else
		call extend(completion_list,g:atp_amsmath_environments,0)
	    endif
	endif
	" MathTools
	" moved to packages/mathtools.vim
" 	if atplib#search#SearchPackage('mathtools', stop_line)
" 	    if end !~ '\s*}'
" 		call extend(completion_list,atplib#Add(g:atp_MathTools_environments,'}'))
" 	    else
" 		call extend(completion_list,g:atp_MathTools_environments)
" 	    endif
" 	endif
	" Packages
	for package in g:atp_packages
	    if atplib#search#SearchPackage(package) && exists("g:atp_".package."_environments")
		if end !~ '\s*}'
		    call extend(completion_list,atplib#Add({'g:atp_'.package.'_environments'},'}'))
		else
		    call extend(completion_list,{'g:atp_'.package.'_environments'})
		endif
	    endif
	endfor
    " {{{3 ------------ ENVIRONMENT OPTIONS
    elseif completion_method == 'environment options'
	let env_name = matchstr(l, '.*\\begin{\s*\zs\w\+\ze\s*}')
	let g:env_name = env_name
	let completion_list=[]
	for package in g:atp_packages
	    if exists("g:atp_".package."_environment_options") && 
			\ (atplib#search#SearchPackage(package) || atplib#search#DocumentClass(b:atp_MainFile) == package)
		for key in keys({"g:atp_".package."_environment_options"})
		    if env_name =~ key
			call extend(completion_list, {"g:atp_".package."_environment_options"}[key])
		    endif
		endfor
	    endif
	endfor
    "{{{3 ------------ PACKAGE OPTIONS VALUES
    elseif completion_method == 'package options values'
	let package = matchstr(line, '\\usepackage\[.*{\zs[^}]*\ze}')
	let option  = matchstr(l,'\zs\<\w\+=\ze[^=]*$')
	let completion_list=[]
	if exists("g:atp_".package."_options_values")
	   for pat in keys({"g:atp_".package."_options_values"})
	       if (option =~ pat)
		   let val={"g:atp_".package."_options_values"}[pat]
		   if type(val) == 3
		       let completion_list={"g:atp_".package."_options_values"}[pat]
		   elseif type(val) == 1
		       execute "let add=".val."()"
		       call extend(completion_list, add)
		   else
		       let completion_list = []
		   endif
		   break
	       endif
	   endfor
       else
	   let g:time_TabCompletion=reltimestr(reltime(time))
	   call atplib#Log("TabCompletion.log", 'package options return')
	   return ""
       endif
    "{{{3 ------------ PACKAGE OPTIONS
    elseif completion_method == 'package options'
	let package = matchstr(line, '\\usepackage.*{\zs[^}]*\ze}')
	let options = split(matchstr(line, '\\usepackage\[\s*\zs[^\]{]*\ze\s*[\]{]'), '\s*,\s*')
	if has("python")
	    let completion_list = get( get( g:atp_package_dict.ScanPackage(package.'.sty', ['options!']) ,package.'.sty',{}) , 'options', [])
	else
	    let completion_list = []
	endif
	if exists("g:atp_".package."_options")
	    " Add options which are not already present:
	    call extend(completion_list, filter(copy({"g:atp_".package."_options"}), 'index(completion_list, v:val) == -1'))
	endif
	" Note: if the completed phrase is in completion pool then we don't
	" want to remove it:
	let phrase = matchstr(l, '\\usepackage\[\(.*,\)\?\zs.*')
	let g:phrase = phrase
	call filter(completion_list, 'index(options, v:val) == -1')
    "{{{3 ------------ PACKAGES
    elseif completion_method == 'package'
	if exists("g:atp_LatexPackages")
	    let completion_list	= copy(g:atp_LatexPackages)
	else
	    echo "[ATP:] makeing list of packages (it might take a while) ... "
	    if g:atp_debugTabCompletion
		let debugTabCompletion_LatexPackages_TimeStart=reltime()
	    endif
	    let g:atp_LatexPackages	= atplib#search#KpsewhichGlobPath("tex", "", "*.sty")
	    let completion_list	= deepcopy(g:atp_LatexPackages)
	    if g:atp_debugTabCompletion
		let g:debugTabCompletion_LatexPackages_Time=reltimestr(reltime(debugTabCompletion_LatexPackages_TimeStart))
		call atplib#Log("TabCompletion.log", "LatexPackages Time: ".g:debugTabCompletion_LatexPackages_Time)
	    endif
	    redraw
	endif
    "{{{3 ------------ PAGESTYLE
    elseif completion_method == 'pagestyle'
	let completion_list=copy(g:atp_pagestyles)
	if atplib#search#SearchPackage('fancyhdr')
	    call extend(completion_list, g:atp_fancyhdr_pagestyles)
	endif
    "{{{3 ------------ PAGENUMBERING
    elseif completion_method == 'pagenumbering'
	let completion_list=copy(g:atp_pagenumbering)
    " {{{3 ------------ TIKZ LIBRARIES
    elseif completion_method == 'tikz libraries'
	let completion_list=deepcopy(g:atp_tikz_libraries)
    " {{{3 ------------ TIKZ KEYWORDS
    elseif completion_method == 'tikzpicture keywords'

	let completion_list=[]
	" TODO: add support for all tikz libraries 
	let tikz_libraries	= atplib#search#GrepPackageList('\\use\%(tikz\|pgf\)library\s*{')
	call map(tikz_libraries, "substitute(v:val, '\\..*$', '', '')")
	for lib in tikz_libraries  
	    if exists("g:atp_tikz_library_".lib."_keywords")
		call extend(completion_list,g:atp_tikz_library_{lib}_keywords)
	    endif   
	endfor
	call extend(completion_list, deepcopy(g:atp_tikz_keywords))
    " {{{3 ------------ TIKZ COMMANDS
    elseif completion_method	== 'tikzpicture commands'
	let completion_list 	= []
	" if tikz is declared and we are in tikz environment.
	let tikz_libraries	= atplib#search#GrepPackageList('\\use\%(tikz\|pgf\)library\s*{')
	for lib in tikz_libraries  
	    if exists("g:atp_tikz_library_".lib."_commands")
		call extend(completion_list, g:atp_tikz_library_{lib}_commands)
	    endif   
	endfor
    " {{{3 ------------ TIKZ COLORS
    elseif completion_method	== 'tikzpicture colors'
	let completion_list 	= copy(b:atp_LocalColors)
    " {{{3 ------------ COMMANDS
    elseif completion_method == 'command'
	"{{{4 
	let tbegin=strpart(l,o+1)
	let completion_list=[]

	" Find end of the preambule.
	if expand("%:p") == atp_MainFile
	    " if the file is the main file
	    let saved_pos=getpos(".")
	    keepjumps call setpos(".", [0,1,1,0])
	    keepjumps let stop_line=search('\\begin\s*{document}','nW')
	    keepjumps call setpos(".", saved_pos)
	else
	    " if the file doesn't contain the preambule
	    if &filetype == 'tex'
		let saved_loclist	= getloclist(0)
		silent! execute '1lvimgrep /\\begin\s*{\s*document\s*}/j ' . fnameescape(atp_MainFile)
		let stop_line	= get(get(getloclist(0), 0, {}), 'lnum', 0)
		call setloclist(0, saved_loclist) 
	    else
		let stop_line = 0
	    endif
	endif
	 
	" Are we in the math mode?
	let math_is_opened	= atplib#IsInMath()

	" -------------------- LOCAL commands {{{4
	if g:atp_local_completion
	    " make a list of local envs and commands:
	    if !exists("b:atp_LocalCommands") 
		" This saves the file.
		call LocalCommands(1, "", "")
	    elseif has("python")
		" This will not save the file.
		call LocalCommands(0, "", "")
	    endif
	    call extend(completion_list, b:atp_LocalCommands)
	endif
	" {{{4 -------------------- MATH commands: amsmath, amssymb, mathtools, nicefrac, SIunits, math non expert mode.
	" if we are in math mode or if we do not check for it.
	if g:atp_no_math_command_completion != 1 &&  ( !g:atp_MathOpened || math_is_opened )
	    call extend(completion_list, g:atp_math_commands)
	    " ----------------------- amsmath && amssymb {{{5
	    " if g:atp_amsmath is set or the document class is ams...
	    if (g:atp_amsmath != 0 || atplib#search#DocumentClass(b:atp_MainFile) =~ '^ams')
		call extend(completion_list, g:atp_amsmath_commands)
		call extend(completion_list, g:atp_ams_negations)
		call extend(completion_list, g:atp_amsfonts)
		call extend(completion_list, g:atp_amsextra_commands)
		if a:expert_mode == 0 
		    call extend(completion_list, g:atp_ams_negations_non_expert_mode)
		endif
	    " else check if the packages are declared:
	    else
		if atplib#search#SearchPackage('amsmath', stop_line)
		    call extend(completion_list, g:atp_amsmath_commands,0)
		endif
		if atplib#search#SearchPackage('amssymb', stop_line)
		    call extend(completion_list, g:atp_ams_negations)
		    if a:expert_mode == 0 
			call extend(completion_list, g:atp_ams_negations_non_expert_mode)
		    endif
		endif
	    endif
	    " ----------------------- nicefrac {{{5
	    if atplib#search#SearchPackage('nicefrac', stop_line)
		call add(completion_list,"\\nicefrac{")
	    endif
	    " ----------------------- SIunits {{{5
	    if atplib#search#SearchPackage('SIunits', stop_line) && ( index(g:atp_completion_active_modes, 'SIunits') != -1 || index(g:atp_completion_active_modes, 'siunits') != -1 )
		call extend(completion_list, g:atp_siuinits)
	    endif
	    for package in g:atp_packages
		if exists("g:atp_".package."_math_commands")
		    call extend(completion_list, {"g:atp_".package."_math_commands"})
		endif
	    endfor

	    " ----------------------- math non expert mode {{{5
	    if a:expert_mode == 0
		call extend(completion_list, g:atp_math_commands_non_expert_mode)
	    endif
	endif
	" {{{4 -------------------- BEAMER commands
" 	if atplib#search#DocumentClass(b:atp_MainFile) == 'beamer'
" 	    call extend(completion_list, g:atp_BeamerCommands)
" 	endif
	" {{{4 -------------------- TIKZ commands
	" if tikz is declared and we are in tikz environment.
	if atplib#search#SearchPackage('\(tikz\|pgf\)')
	    let in_tikz=searchpair('\\begin\s*{tikzpicture}','','\\end\s*{tikzpicture}','bnW',"", max([1,(line(".")-g:atp_completion_limits[2])])) || atplib#complete#CheckOpened('\\tikz{','}',line("."),g:atp_completion_limits[0])

	    if in_tikz
		" find all tikz libraries at once:
		let tikz_libraries	= atplib#search#GrepPackageList('\\use\%(tikz\|pgf\)library\s*{')

		" add every set of library commands:
		for lib in tikz_libraries  
		    if exists("g:atp_tikz_library_".lib."_commands")
			call extend(completion_list, g:atp_tikz_library_{lib}_commands)
		    endif   
		endfor

		" add common tikz commands:
		call extend(completion_list, g:atp_tikz_commands)

		" if in text mode add normal commands:
		if searchpair('\\\@<!{', '', '\\\@<!}', 'bnW', "", max([ 1, (line(".")-g:atp_completion_limits[0])]))
		    call extend(completion_list, g:atp_Commands)
		endif
	    endif 
	endif
	" {{{4 -------------------- fancyhdr & makeidx Commands
"	if we are not in math mode or if we do not care about it or we are in non expert mode.
	if (!g:atp_MathOpened || !math_is_opened ) || a:expert_mode == 0
	    call extend(completion_list, g:atp_Commands)
	    " FANCYHDR
	    if atplib#search#SearchPackage('fancyhdr', stop_line)
		call extend(completion_list, g:atp_fancyhdr_commands)
	    endif
	    if atplib#search#SearchPackage('makeidx', stop_line)
		call extend(completion_list, g:atp_makeidx_commands)
	    endif
	endif
	" {{{4 -------------------- ToDoNotes package commands
	if ( index(g:atp_completion_active_modes, 'todonotes') != -1 ) && atplib#search#SearchPackage('todonotes', stop_line)
	    call extend(completion_list, g:atp_TodoNotes_commands)
	endif
	"}}}4 
   	"{{{4 -------------------- picture
	if searchpair('\\begin\s*{\s*picture\s*}','','\\end\s*{\s*picture\s*}','bnW',"", max([ 1, (line(".")-g:atp_completion_limits[2])]))
	    call extend(completion_list, g:atp_picture_commands)
	endif 
   	"{{{4 -------------------- PACKAGES
	let time = reltime()
	for package in g:atp_packages
	    if atplib#search#SearchPackage(package)
		if exists("g:atp_".package."_commands")
		    " Add commands whcih are not already present:
		    let add_completion_list = {"g:atp_".package."_commands"}
		elseif has("python")
		    let add_completion_list = get(get(g:atp_package_dict.ScanPackage(package.'.sty', ['commands']) ,package.'.sty',{}) , 'options', [])
		else
		    let add_completion_list = []
		endif
		call extend(completion_list, filter(add_completion_list, 'index(completion_list, v:val) == -1'))
	    endif
	endfor
	let g:time_PackagesCommands=reltimestr(reltime(time))
   	"{{{4 -------------------- DOCUMENT CLASS
	" Todo: get document class from the main file and add
	" g:atp_package_dir.ScanPackage(documentclass.".cls", ['commands'])
	if &filetype == "tex"
	    let loclist = getloclist(0)
	    try
		exe '1lvimgrep /^\s*\\documentclass/j '.fnameescape(b:atp_MainFile)

		let documentclass = matchstr(get(getloclist(0), 0, {'text': ''})['text'], '\\documentclass\s*\[[^\]]*\]\s*{\s*\zs[^}]*\ze\s*}')
	    catch /E480/
		let documentclass = ""
	    endtry
	    call setloclist(0, loclist)
	    if !empty(documentclass)
		if has("python")
		    let add_completion_list = get( get( g:atp_package_dict.ScanPackage(documentclass.'.cls', ['commands']) ,package.'.sty',{}) , 'options', [])
		else
		    let add_completion_list = []
		endif
		call filter(add_completion_list, 'index(completion_list, v:val) == -1')
		call extend(completion_list, add_completion_list)
		if exists("g:atp_".documentclass."_commands")
		    " Add commands whcih are not already present:
		    call extend(completion_list, filter(copy({"g:atp_".documentclass."_commands"}), 'index(completion_list, v:val) == -1'))
		endif
	    endif
	endif
   	"{{{4 -------------------- CLASS
	let documentclass=atplib#search#DocumentClass(b:atp_MainFile)
	if exists("g:atp_".documentclass."_commands")
	    call extend(completion_list, {"g:atp_".documentclass."_commands"})
	endif
	" ToDo: add layout commands and many more packages. (COMMANDS FOR
	" PREAMBULE)
	"{{{4 -------------------- final stuff
	let env_name=substitute(pline,'.*\%(\\\%(begin\|end.*\){\(.\{-}\)}.*\|\\\%(\(item\)\s*\)\%(\[.*\]\)\?\s*$\)','\1\2','') 
	if env_name =~ '\\\%(\%(sub\)\?paragraph\|\%(sub\)*section\|chapter\|part\)'
	    let env_name=substitute(env_name,'.*\\\(\%(sub\)\?paragraph\|\%(sub\)*section\|chapter\|part\).*','\1','')
	endif
	let env_name=substitute(env_name,'\*$','','')
	" if the pattern did not work do not put the env name.
	" for example \item cos\lab<Tab> the pattern will not work and we do
	" not want env name. 
	if env_name == pline
	    let env_name=''
	endif

	if has_key(g:atp_shortname_dict,env_name)
	    if g:atp_shortname_dict[env_name] != 'no_short_name' && g:atp_shortname_dict[env_name] != '' 
		let short_env_name=g:atp_shortname_dict[env_name]
		let no_separator=0
	    else
		let short_env_name=''
		let no_separator=1
	    endif
	else
	    let short_env_name=''
	    let no_separator=1
	endif

" 	if index(g:atp_no_separator_list, env_name) != -1
" 	    let no_separator = 1
" 	endif

	if g:atp_env_short_names == 1
	    if no_separator == 0 && g:atp_no_separator == 0
		let short_env_name=short_env_name . g:atp_separator
	    endif
	else
	    let short_env_name=''
	endif

	call extend(completion_list, [ '\label{' . short_env_name ],0)
    " {{{3 ------------ COMMAND VALUES
    elseif completion_method == 'command values'
	if l !~ '\\renewcommand{[^}]*}{[^}]*$'
" 	    let command = matchstr(l, '.*\\\w\+\%(\[\%([^\]]\|\[[^\]]*\]\)*\]\)\?\%({\%([^}]\|{\%([^}]\|{[^}]*\)*}}\)*}\)*{\ze\%([^}]\|{\%([^}]\|{[^}]*}\)*}\)*$')
	    let command = matchstr(l, '.*\\\w\+\%(\[\%([^\]]\|\[[^\]]*\]\)*\]\)\?\%({\%([^}]\|{\%([^}]\|{[^}]*\)*}}\)*}\)*{\ze\%([^}]\|{\%([^}]\|{[^}]*}\)*}\)*$')
	else
	    let command = matchstr(l, '.*\\renewcommand{\s*\zs\\\?\w*\ze\s*}')
	endif
	let g:command = command
	let completion_list = []
	let command_pat='\\\w\+[{\|\[]'
	for package in g:atp_packages
	    let test = 0
	    if exists("g:atp_".package."_loading")
		for key in keys(g:atp_{package}_loading)
		    let package_line_nr = atplib#search#SearchPackage(g:atp_{package}_loading[key])
		    if g:atp_{package}_loading[key] == "" || package_line_nr == 0
			let test = package_line_nr
		    else
			let package_line = getline(package_line_nr)
			let test = (package_line=~'\\usepackage\[[^\]]*,\='.g:atp_{package}_loading[key].'[,\]]')
		    endif
		    if test
			break
		    endif
		endfor
	    endif

	    if exists("g:atp_".package."_command_values") && 
		\ ( 
		    \ atplib#search#SearchPackage(package) || test || 
		    \ atplib#search#DocumentClass(b:atp_MainFile) == package || package == "common" 
		\ )
		for key in keys({"g:atp_".package."_command_values"})
		    " uncomment this to debug in which package file there is a mistake.
		    if command =~ key
			let command_pat = key
			let val={"g:atp_".package."_command_values"}[key]
			if g:atp_debugTabCompletion
			    call atplib#Log("TabCompletion.log", 'command_pat='.command_pat." package=".package)
			    call atplib#Log("TabCompletion.log", 'val='.string(val))
			endif
			if type(val) == 3
			    call extend(completion_list, val)
			elseif type(val) == 1 && exists("*".val)
			    execute "let add=".val."()"
			    call extend(completion_list, add)
			else
			    call atplib#Log("TabCompletion.log", "command values: wrong type error")
			endif
		    endif
		endfor
	    endif
	endfor
    " {{{3 ------------ ABBREVIATIONS
    elseif completion_method == 'abbreviations'
	let completion_list  = sort(copy(b:atp_LocalEnvironments), "atplib#CompareStarAfter")+[ "document","description","letter","picture","list","minipage","titlepage","thebibliography","bibliography","center","flushright","flushleft","tikzpicture","frame","itemize","enumerate","quote","quotation","verse","abstract","verbatim","figure","array","table","tabular","equation","equation*","align","align*","alignat","alignat*","gather","gather*","multline","multline*","split","flalign","flalign*","corollary","theorem","proposition","lemma","definition","proof","remark","example","exercise","note","question","notation"]
	for package in g:atp_packages
	    if exists("g:atp_".package."_environments")
		call extend(completion_list, {"g:atp_".package."_environments"})
	    endif
	endfor
	call map(completion_list, "g:atp_iabbrev_leader.v:val.g:atp_iabbrev_leader")
    " {{{3 ------------ LABELS /are done later only the completions variable /
    elseif completion_method ==  'labels'
	let completion_list = []
    " {{{3 ------------ INPUTFILES
    elseif completion_method ==  'inputfiles'
	let completion_list=[]
	call  extend(completion_list, atplib#search#KpsewhichGlobPath('tex', b:atp_OutDir . ',' . g:atp_texinputs, '*.tex', ':t:r', '^\%(\/home\|\.\|.*users\)', '\%(^\\usr\|texlive\|miktex\|kpsewhich\|generic\)'))
	call sort(completion_list)
    " {{{3 ------------ TEX INCLUDEGRAPHICS
    elseif completion_method == 'includegraphics'
	" Search for \graphicspath but only in the preamble
	let matches=atplib#search#GrepPreambule('\\graphicspath')
	if len(matches)
	    for match in matches
		let dirs = map(split(matchstr(match['text'], '\graphicspath\s*{\zs.*\ze}'), '}'), "substitute(v:val, '^\s*{', '', '')")
		call map(dirs, "substitute(v:val, '\/\/', '/**', 'g')")
	    endfor
	else
	    let dirs = [fnamemodify(atplib#FullPath(b:atp_MainFile), ":h")]
	endif
	let gr_dirs = join(dirs,',')
	let g:gr_dirs = gr_dirs
	if b:atp_TexCompiler == "latex"
	    let gr = ["*.eps", "*.EPS"]
	else
	    let gr = ["*.gif", "*jpeg", "*.jpg", "*.png", "*.pdf", "*.pdf_tex", "*.eps",
			\ "*.GIF", "*JPEG", "*.JPG", "*.PNG", "*.PDF", "*.PDF_TEX", "*.EPS"]
	endif
	let completion_list=[]
	if begin !~ '\.\(gif\|jpe\?g\|png\|pdf\|pdf_tex\|eps\)$'
	    for ext in gr
		let completion_list+=split(globpath(gr_dirs, begin.ext), "\n")
	    endfor
	else
	    let completion_list+=split(globpath(gr_dirs, begin), "\n")
	endif
	call map(completion_list, "substitute(v:val, '^\s*\.\/', '', '')")
    " {{{3 ------------ BIBFILES
    elseif completion_method ==  'bibfiles'
	let  completion_list=[]
	call extend(completion_list, atplib#search#KpsewhichGlobPath('bib', b:atp_OutDir . ',' . g:atp_bibinputs, '*.bib', ':t:r', '^\%(\/home\|\.\|.*users\)', '\%(^\\usr\|texlive\|miktex\|kpsewhich\|generic\|miktex\)'))
	call sort(completion_list)
    " {{{3 ------------ BIBSTYLES
    elseif completion_method == 'bibstyles'
	let completion_list=atplib#search#KpsewhichGlobPath("bst", "", "*.bst")
    "{{{3 ------------ DOCUMENTCLASS OPTIONS
    elseif completion_method == 'documentclass options'
	let documentclass = matchstr(line, '\\documentclass\[[^{]*{\zs[^}]*\ze}')
	let g:documentclass = documentclass
	if has("python")
	    let completion_list = get( get( g:atp_package_dict.ScanPackage(documentclass.'.cls', ['options!']) ,documentclass.'.cls',{}) , 'options', [])
	else
	    let completion_list = []
	endif
	if exists("g:atp_".documentclass."_options")
	    " Add options whcih are not already present:
	    call extend(completion_list, filter(copy({"g:atp_".documentclass."_options"}), 'index(completion_list, v:val) == -1'))
	endif
    "{{{3 ------------ DOCUMENTCLASS
    elseif completion_method == 'documentclass'
	if exists("g:atp_LatexClasses")
	    let completion_list	= copy(g:atp_LatexClasses)
	else
	    echo "[ATP:] makeing list of document classes (it might take a while) ... "
	    if g:atp_debugTabCompletion
		let debugTabCompletion_LatexClasses_TimeStart=reltime()
	    endif
	    let g:atp_LatexClasses	= atplib#search#KpsewhichGlobPath("tex", "", "*.cls")
	    if g:atp_debugTabCompletion
		let g:debugTabCompletion_LatexClasses_Time=reltimestr(reltime(debugTabCompletion_LatexClasses_TimeStart))
		call atplib#Log("TabCompletion.log", "LatexClasses Time: ".g:debugTabCompletion_LatexClasses_Time)
	    endif
	    redraw
	    let completion_list		= deepcopy(g:atp_LatexClasses)
	endif
	" \documentclass must be closed right after the name ends:
	if nchar != "}"
	    call map(completion_list,'v:val."}"')
	endif
    "{{{3 ------------ FONT FAMILY
    elseif completion_method == 'font family'
	echo "[ATP:] searching through fd files ..."
	let time=reltime()
	let bpos=searchpos('\\selectfon\zst','bnW',line("."))[1]
	let epos=searchpos('\\selectfont','nW',line("."))[1]-1
	if epos == -1
	    let epos=len(line)
	endif
	let fline=strpart(line,bpos,epos-bpos)
	let encoding=matchstr(fline,'\\\%(usefont\|DeclareFixedFont\s*{[^}]*}\|fontencoding\)\s*{\zs[^}]*\ze}')
	if encoding == ""
	    let encoding=g:atp_font_encoding
	endif
	let completion_list=[]
	let fd_list=atplib#fontpreview#FdSearch('^'.encoding.begin)
	" The above function takes .5s to complete. The code below takes more 1s.
	for file in fd_list
            call extend(completion_list,map(atplib#fontpreview#ShowFonts(file),'matchstr(v:val,"usefont\\s*{[^}]*}\\s*{\\zs[^}]*\\ze}")'))
	endfor
" 	call filter(completion_list,'count(completion_list,v:val) == 1 ')
" 	This was taking another .8s.
	redraw
	if len(completion_list) == 0
	    echo "[ATP:] nothing found."
	endif
	let g:time_font_family=reltimestr(reltime(time))
    "{{{3 ------------ FONT SERIES
    elseif completion_method == 'font series'
	let time=reltime()
	let bpos=searchpos('\\selectfon\zst','bnW',line("."))[1]
	let epos=searchpos('\\selectfont','nW',line("."))[1]-1
	if epos == -1
	    let epos=len(line)
	endif
	let fline=strpart(line,bpos,epos-bpos)
	let encoding=matchstr(fline,'\\\%(usefont\|DeclareFixedFont\s*{[^}]*}\|fontencoding\)\s*{\zs[^}]*\ze}')
	if encoding == ""
	    let encoding=g:atp_font_encoding
	endif
	let font_family=matchstr(fline,'\\\%(usefont\s*{[^}]*}\|DeclareFixedFont\s*{[^}]*}\s*{[^}]*}\|fontfamily\)\s*{\zs[^}]*\ze}')
	echo "[ATP:] searching through fd files ..."
	let completion_list=[]
	let fd_list=atplib#fontpreview#FdSearch(encoding.font_family)
	" The above function takes .5s to complete.
	for file in fd_list
	    call extend(completion_list, map(atplib#fontpreview#ShowFonts(file),'matchstr(v:val,"usefont{[^}]*}{[^}]*}{\\zs[^}]*\\ze}")'))
	endfor
	call filter(completion_list,'count(completion_list,v:val) == 1 ')
	redraw
    "{{{3 ------------ FONT SHAPE
    elseif completion_method == 'font shape'
	let bpos=searchpos('\\selectfon\zst','bnW',line("."))[1]
	let epos=searchpos('\\selectfont','nW',line("."))[1]-1
	if epos == -1
	    let epos=len(line)
	endif
	let fline=strpart(line,bpos,epos-bpos)
	let encoding=matchstr(fline,'\\\%(usefont\|DeclareFixedFont\s*{[^}]*}\|fontencoding\)\s*{\zs[^}]*\ze}')
	if encoding == ""
	    let encoding=g:atp_font_encoding
	endif
	let font_family=matchstr(fline,'\\\%(usefont{[^}]*}\|DeclareFixedFont\s*{[^}]*}\s*{[^}]*}\|fontfamily\)\s*{\zs[^}]*\ze}')
	let font_series=matchstr(fline,'\\\%(usefont\s*{[^}]*}\s*{[^}]*}\|DeclareFixedFont\s*{[^}]*}\s*{[^}]*}\s*{[^}]*}\|fontseries\)\s*{\zs[^}]*\ze}')
	echo "[ATP:] searching through fd files ..."
	let completion_list=[]
	let fd_list=atplib#fontpreview#FdSearch('^'.encoding.font_family)

	for file in fd_list
	    call extend(completion_list,map(atplib#fontpreview#ShowFonts(file),'matchstr(v:val,"usefont{[^}]*}{'.font_family.'}{'.font_series.'}{\\zs[^}]*\\ze}")'))
	endfor
	call filter(completion_list,'count(completion_list,v:val) == 1 ')
	redraw
    " {{{3 ------------ FONT ENCODING
    elseif completion_method == 'font encoding'
	let bpos=searchpos('\\selectfon\zst','bnW',line("."))[1]
	let epos=searchpos('\\selectfont','nW',line("."))[1]-1
	if epos == -1
	    let epos=len(line)
	endif
	let fline=strpart(line,bpos,epos-bpos)
	let font_family=matchstr(fline,'\\\%(usefont\s*{[^}]*}\|DeclareFixedFont\s*{[^}]*}\s*{[^}]*}\|fontfamily\)\s*{\zs[^}]*\ze}')
	if font_family != ""
	    echo "[ATP:] searching through fd files ..."
	    let fd_list=atplib#fontpreview#FdSearch(font_family)
	    let completion_list=map(copy(fd_list),'toupper(substitute(fnamemodify(v:val,":t"),"'.font_family.'.*$","",""))')
	    redraw
	else
" 	    let completion_list=[]
" 	    for fd_file in fd_list
" 		let enc=substitute(fnamemodify(fd_file,":t"),"\\d\\zs.*$","","")
" 		if enc != fnamemodify(fd_file,":t")
" 		    call add(completion_list,toupper(enc))
" 		endif
" 	    endfor
	    let completion_list=g:atp_completion_font_encodings
	endif
    " {{{3 ------------ BIBITEMS
    elseif completion_method == 'bibitems'
	let time_bibitems=reltime()
	let col = col('.') - 1
	while col > 0 && line[col - 1] !~ '{\|,'
		let col -= 1
	endwhile
	let pat = strpart(l,col)
	let g:pat = pat
	let searchbib_time=reltime()
	if len(filter(values(copy(b:TypeDict)), "v:val == 'bib'"))
	    if !exists("b:ListOfFiles") && !exists("b:TypeDict")
		call TreeOfFiles(b:atp_MainFile)
	    endif
	    if has("python") && g:atp_bibsearch == "python" && pat != ""
		let bibfiles=[]
		for f in b:ListOfFiles
		    if b:TypeDict[f] == 'bib'
			call add(bibfiles, f)
		    endif
		endfor
		let bibitems_list=values(atplib#bibsearch#searchbib_py(pat, bibfiles))
	    else
		let bibdict={}
		for f in b:ListOfFiles
		    try
			if b:TypeDict[f] == 'bib'
			    let bibdict[f]=readfile(f)
			endif
		    catch /E716:/
			echoerr "[ATP]: key ".f." not present in dictionary b:TypeDict. Try to run :InputFiles."
			return ''
		    endtry
		endfor
		let bibitems_list=values(atplib#bibsearch#searchbib(pat, bibdict))
	    endif
	    let g:bibitems_list=bibitems_list
	    let g:time_searchbib_py=reltimestr(reltime(searchbib_time))
	    if g:atp_debugTabCompletion
		let g:pat = pat
	    endif
	    let pre_completion_list=[]
	    let completion_dict=[]
	    let completion_list=[]
	    let time_bibitems_for=reltime()
	    for dict in bibitems_list
		for key in keys(dict)
		    " ToDo: change dict[key][...] to get() to not get errors
		    " if it is not present or to handle situations when it is not
		    " present!
		    call add(pre_completion_list, dict[key]['bibfield_key']) 
		    let bibkey=dict[key]['bibfield_key']
		    let bibkey=substitute(strpart(bibkey,max([stridx(bibkey,'{'),stridx(bibkey,'(')])+1),',\s*','','')
		    if nchar != ',' && nchar != '}'
			let bibkey.="}"
		    endif
		    let title=get(dict[key],'title', 'notitle')
		    let title=substitute(matchstr(title,'^\s*\ctitle\s*=\s*\%("\|{\|(\)\zs.*\ze\%("\|}\|)\)\s*\%(,\|$\)'),'{\|}','','g')
		    let year=get(dict[key],'year',"")
		    let year=matchstr(year,'^\s*\cyear\s*=\s*\%("\|{\|(\)\zs.*\ze\%("\|}\|)\)\s*\%(,\|$\)')
		    let abbr=get(dict[key],'author',"noauthor")
		    let author = matchstr(abbr,'^\s*\cauthor\s*=\s*\%("\|{\|(\)\zs.*\ze\%("\|}\|)\)\s*,')
		    if abbr=="noauthor" || abbr == ""
			let abbr=get(dict[key],'editor',"")
			let author = matchstr(abbr,'^\s*\ceditor\s*=\s*\%("\|{\|(\)\zs.*\ze\%("\|}\|)\)\s*,')
		    endif
		    if len(author) >= 40
			if match(author,'\sand\s')
			    let author=strpart(author,0,match(author,'\sand\s')) . ' et al.'
			else
			    let author=strpart(author,0,40)
			endif
		    endif
		    let author=substitute(author,'{\|}','','g')
		    if dict[key]['bibfield_key'] =~? '\<article\>'
			let type="[a]"
		    elseif dict[key]['bibfield_key'] =~? '\<book\>'
			let type="[B]"
		    elseif dict[key]['bibfield_key'] =~? '\<booklet\>'
			let type="[b]"
		    elseif  dict[key]['bibfield_key'] =~? '\<\%(proceedings\|conference\)\>'
			let type="[p]"
		    elseif dict[key]['bibfield_key'] =~? '\<unpublished\>'
			let type="[u]"
		    elseif dict[key]['bibfield_key'] =~? '\<incollection\>'
			let type="[c]"
		    elseif dict[key]['bibfield_key'] =~? '\<phdthesis\>'
			let type="[PhD]"
		    elseif dict[key]['bibfield_key'] =~? '\<masterthesis\>'
			let type="[M]"
		    elseif dict[key]['bibfield_key'] =~? '\<misc\>'
			let type="[-]"
		    elseif dict[key]['bibfield_key'] =~? '\<techreport\>'
			let type="[t]"
		    elseif dict[key]['bibfield_key'] =~? '\<manual\>'
			let type="[m]"
		    else
			let type="   "
		    endif

		    let abbr=type." ".author." (".year.") "

		    call add(completion_dict, { "word" : bibkey, "menu" : title, "abbr" : abbr }) 
		endfor
	    endfor
            let g:completion_dict=completion_dict
	    for key in pre_completion_list
		call add(completion_list,substitute(strpart(key,max([stridx(key,'{'),stridx(key,'(')])+1),',\s*','',''))
	    endfor
	else
	    " add the \bibitems found in include files
	    let time_bibitems_SearchBibItems=reltime()
            let completion_dict=[]
            let dict=atplib#bibsearch#SearchBibItems()
	    let g:dict = copy(dict)
            for key in keys(dict)
		if a:expert_mode && ( key =~ '^'.begin || dict[key]['label'] =~ '^'.begin ) || 
			\ !a:expert_mode && ( key =~ begin || dict[key]['label'] =~ begin )
		    call add(completion_dict, { "word" : key, "menu" : dict[key]['rest'], "abbrev" : dict[key]['label'] })
		endif
            endfor
	    let g:time_bibitems_SearchBibItems=reltimestr(reltime(time_bibitems_SearchBibItems))
	endif
	let g:time_bibitems=reltimestr(reltime(time_bibitems))
    " {{{3 ------------ TODONOTES TODO & MISSING FIGURE OPTIONS
    elseif completion_method == 'todo options'
	let completion_list = copy(g:atp_TodoNotes_todo_options)
    elseif completion_method == 'missingfigure options'
	let completion_list = copy(g:atp_TodoNotes_missingfigure_options)
    endif
    " }}}3
    if exists("completion_list")
	let b:completion_list=completion_list	" DEBUG
	call atplib#Log("TabCompletion.log", "completion_list=".string(completion_list))
    endif
" {{{2 make the list of matching completions
    "{{{3 --------- completion_method = !close environments !env_close
    if completion_method != 'close environments' && completion_method != 'env_close'
	let completions=[]
	    " {{{4 --------- packages, package options, bibstyles, font (family, series, shapre, encoding), document class, documentclass options
	    if (completion_method == 'package' 		||
		    \ completion_method == 'package options'||
		    \ completion_method == 'environment options'||
		    \ completion_method == 'documentclass options'||
		    \ completion_method == 'bibstyles' 	||
		    \ completion_method =~ 'beamer\%(\|inner\|outer\|color\|font\)themes' ||
		    \ completion_method == 'font family' 	||
		    \ completion_method == 'font series' 	||
		    \ completion_method == 'font shape'	||
		    \ completion_method == 'font encoding'||
		    \ completion_method == 'pagestyle'||
		    \ completion_method == 'pagenumbering'||
		    \ completion_method == 'documentclass' )
		if a:expert_mode
		    let completions	= filter(copy(completion_list),' v:val =~? "^".begin') 
		else
		    let completions	= filter(copy(completion_list),' v:val =~? begin') 
		endif
	    " {{{4 --------- command values
	    elseif completion_method == 'command values' 
		if a:expert_mode
		    let completions	= filter(copy(completion_list),' v:val =~? "^".cmd_val_begin') 
		else
		    let completions	= filter(copy(completion_list),' v:val =~? cmd_val_begin') 
		endif
	    " {{{4 --------- package options values
	    elseif ( completion_method == 'package options values' )
		if a:expert_mode
		    let completions	= filter(copy(completion_list),' v:val =~? "^".ebegin') 
		else
		    let completions	= filter(copy(completion_list),' v:val =~? ebegin') 
		endif
	    " {{{4 --------- environment names, bibfiles 
	    elseif ( completion_method == 'environment_names'	||
			\ completion_method == 'bibfiles' 	)
		if a:expert_mode
		    let completions	= filter(copy(completion_list),' v:val =~# "^".begin') 
		else
		    let completions	= filter(copy(completion_list),' v:val =~? begin') 
		endif
	    " {{{4 --------- colors
	    elseif completion_method == 'tikzpicture colors'
		if a:expert_mode
		    let completions	= filter(copy(completion_list),' v:val =~# "^".color_begin') 
		else
		    let completions	= filter(copy(completion_list),' v:val =~? color_begin') 
		endif
	    " {{{4 --------- tikzpicture libraries, inputfiles 
	    " match not only in the beginning
	    elseif (completion_method == 'tikz libraries' ||
			\ completion_method == 'inputfiles')
		let completions	= filter(copy(completion_list),' v:val =~? begin') 
" 		if nchar != "}" && nchar != "," && completion_method != 'inputfiles'
" 		    call map(completions,'v:val')
" 		endif
	    " {{{4 --------- Commands 
	    " must match at the beginning (but in a different way)
	    " (only in expert_mode).
	    elseif completion_method == 'command' 
		if a:expert_mode == 1 
		    let completions	= filter(copy(completion_list),'v:val =~# "\\\\".tbegin')
		elseif a:expert_mode != 1 
		    let completions	= filter(copy(completion_list),'v:val =~? tbegin')
		endif
	    " {{{4 --------- Abbreviations
	    elseif completion_method == 'abbreviations'
		let completions		= filter(copy(completion_list), 'v:val =~# "^" . abegin')
	    " {{{4 --------- Tikzpicture Keywords
	    elseif completion_method == 'tikzpicture keywords' || 
			\ completion_method == 'todo options' ||
			\ completion_method == 'missingfigure options'
		if g:atp_completion_tikz_expertmode
		    let completions	= filter(copy(completion_list),'v:val =~# "^".tbegin') 
		else
		    let completions	= filter(copy(completion_list),'v:val =~? tbegin') 
		endif
	    " {{{4 --------- Tikzpicture Commands
	    elseif completion_method == 'tikzpicture commands'
		if a:expert_mode == 1 
		    let completions	= filter(copy(completion_list),'v:val =~# "^".tbegin') 
		elseif a:expert_mode != 1 
		    let completions	= filter(copy(completion_list),'v:val =~? tbegin') 
		endif
	    " {{{4 --------- Labels
	    elseif completion_method == 'labels'
		" Complete label by string or number:
		
		let aux_data	= atplib#tools#GrepAuxFile()
		let completion_dict = []
		let pattern 	= matchstr(l, '\\\%(eq\|page\|auto\|autopage\)\=ref\*\=\s*{\zs\S*$\|\\hyperref\s*\[\zs\S*$')
		for data in aux_data
		    " match label by string or number
		    if ( data[0] =~ '^' . pattern || data[1] =~ '^'. pattern ) && a:expert_mode || ( data[0] =~ pattern || data[1] =~ pattern ) && !a:expert_mode
			if l =~ '\\\%(eq\|page\|auto\|autopage\)\=ref\*\=\s*{\S*$'
			    let close = ( nchar == '}' ? '' : '}' )
			else
			    let close = ( nchar == ']' ? '' : ']' )
			endif
			call add(completion_dict, { "word" : data[0].close, "abbr" : data[0], "menu" : ( data[2] == 'equation' && data[1] != "" ? "(".data[1].")" : data[1] ) , "kind" : data[2][0] })
		    endif
		endfor 
	    " {{{4 --------- includegraphics
	    elseif completion_method == 'includegraphics'
		let completions=copy(completion_list)
	    endif
    "{{{3 --------- else: try to close environment
    else
	call atplib#complete#CloseLastEnvironment('a', 'environment')
	let b:tc_return="1"
        let g:time_TabCompletion=reltimestr(reltime(time))
	return ''
    endif
    "{{{3 --------- SORTING and TRUNCATION
    " ToDo: we will not truncate if completion method is specific, this should be
    " made by a variable! Maybe better is to provide a positive list !!!
    if g:atp_completion_truncate && a:expert_mode && 
		\ index(['bibfiles', 'bibitems', 'bibstyles', 'font family',
		\ 'environment_names', 'environment options', 'font series', 
		\ 'font shape', 'font encoding', 'inputfiles', 'includefiles', 
		\ 'labels', 'package options', 'package options values',
		\ 'documentclass options', 'documentclass options values', 
		\ 'tikz libraries' ],completion_method) == -1
	call filter(completions, 'len(substitute(v:val,"^\\","","")) >= g:atp_completion_truncate')
    endif
"     THINK: about this ...
"     if completion_method == "tikzpicture keywords"
" 	let bracket	= atplib#complete#CloseLastBracket(g:atp_bracket_dict, 1)
" 	if bracket != ""
" 	    call add(completions, bracket)
" 	endif
"     endif
    " if the list is long it is better if it is sorted, if it short it is
    " better if the more used things are at the beginning.
    if g:atp_sort_completion_list && len(completions) >= g:atp_sort_completion_list && completion_method != 'labels'
	if completion_method == 'abbreviations'
	    let completions=sort(completions, "atplib#CompareStarAfter")
	else
	    let completions=sort(completions)
	endif
    endif
    " DEBUG
    let b:completions=completions 
   " {{{2 COMPLETE 
    call cursor(pos_saved[1], pos_saved[2])
    " {{{3 package, tikz libraries, environment_names, colors, bibfiles, bibstyles, documentclass, font family, font series, font shape font encoding, input files, includegraphics
    if
		\ completion_method == 'package' 	|| 
		\ completion_method == 'environment options' ||
		\ completion_method == 'environment_names' ||
		\ completion_method == 'tikz libraries' || 
		\ completion_method == 'pagestyle'	||
		\ completion_method == 'pagenumbering'	||
		\ completion_method == 'bibfiles' 	|| 
		\ completion_method == 'bibstyles' 	|| 
		\ completion_method == 'documentclass'  || 
		\ completion_method == 'font family'  	||
		\ completion_method == 'font series'  	||
		\ completion_method == 'font shape'   	||
		\ completion_method == 'font encoding'	||
		\ completion_method == 'todo options' 	||
		\ completion_method == 'missingfigure options' ||
		\ completion_method == 'inputfiles' 	||
		\ completion_method == 'includegraphics' 
	let column = nr+2
	call complete(column,completions)
    "{{{3 abbreviations
    elseif completion_method == 'abbreviations'
	let col=match(l, '^.*\zs=')+1
	call complete(col, completions)
	let column=col
    "{{{3 labels
    elseif completion_method == 'labels'
	let col=match(l, '\\\(eq\|page\|auto\|autopage\)\=ref\*\=\s*{\zs\S*$\|\\hyperref\s*\[\zs\S*$')+1
	call complete(col, completion_dict)
	let column=col
	return ''
    " {{{3 bibitems
    elseif !normal_mode && completion_method == 'bibitems'
        if exists("completion_dict")
            " for bibtex, biblatex
            call complete(col+1,completion_dict)
	    let column=col+1
        else
            " for thebibliography environment
            call complete(col+1,completion_list)
	    let column=col+1
        endif
    " {{{3 commands, tikzcpicture commands
    elseif !normal_mode && (completion_method == 'command' || completion_method == 'tikzpicture commands')
	" We are not completing greek letters, but we add them if cbegin is
	" one. 
	call extend(completion_list, g:atp_greek_letters)
	if count(completion_list, cbegin) >= 1
	    " Add here brackets - somebody might want to
	    " close a bracket after \nu and not get \numberwithin{ (which is
	    " rarely used).
	    let b:comp_method = "brackets in commands"
	    if (!normal_mode &&  index(g:atp_completion_active_modes, 'brackets') != -1 ) ||
		    \ (normal_mode && index(g:atp_completion_active_modes_normal_mode, 'brackets') != -1 )
		let bracket=atplib#complete#GetBracket(append, g:atp_bracket_dict)
		if bracket != "0" && bracket != ""
		    let completions = extend([cbegin.bracket], completions)
		endif
	    endif
	    call add(completions, cbegin)
	endif
	call complete(o+1,completions)
	let column=o+1
    " {{{3 tikzpicture keywords
    elseif !normal_mode && (completion_method == 'tikzpicture keywords')
	let t=match(l,'\zs\<\w*$')
	" in case '\zs\<\w*$ is empty
	if t == -1
	    let t=col(".")
	endif
	call complete(t+1,completions)
	let column=t+1
	let b:tc_return="tikzpicture keywords"
    " {{{3 tikzpicture colors
    elseif !normal_mode && (completion_method == 'tikzpicture colors')
	call complete(color_nr+2, completions)
	let column=color_nr+2
    " {{{3 package and document class options
    elseif !normal_mode && ( completion_method == 'package options' || completion_method == 'documentclass options' 
		\ || completion_method == 'environment options' )
	let col=len(matchstr(l,'^.*\\\%(documentclass\|usepackage\)\[.*,\ze'))
	if col==0
	    let col=len(matchstr(l,'^.*\\\%(documentclass\|usepackage\)\[\ze'))
	endif
	call complete(col+1, completions)
	let column = col+1
    " {{{3 command values
    elseif  !normal_mode && ( completion_method == 'command values' )
	let col = len(l)-len(cmd_val_begin)
	call complete(col+1, completions)
	let column = col+1
    " {{{3 package and document class options values
    elseif !normal_mode && (completion_method == 'package options values')
	let col=len(matchstr(l,'\\\%(documentclass\|usepackage\)\[.*=\%({[^}]*,\|{\)\?\ze'))
	if col==0
	    let col=len(matchstr(l,'\\\%(documentclass\|usepackage\)\[\ze'))
	endif
	call complete(col+1, completions)
	let column = col+1
    else
	let column = col(".")
    endif
    " If the completion method was a command (probably in a math mode) and
    " there was no completion, check if environments are closed.
    " {{{3 Final call of CloseLastEnvrionment / CloseLastBracket
    let len=len(completions)
    let matched_word = strpart(getline(line(".")), column-1, pos_saved[2]-column)
    let g:matched_word = matched_word
    let g:column = column
    let g:pos_saved = copy(pos_saved)
    if len == 0 && (!count(['package', 'bibfiles', 'bibstyles', 'inputfiles'], completion_method) || a:expert_mode == 1 ) || len == 1
	let b:comp_method .= " final"
	if count(['command', 'tikzpicture commands', 'tikzpicture keywords', 'command values'], completion_method) && 
	    \ (len == 0 || len == 1 && completions[0] =~ '^\\\='. begin . '$' )

	    let filter 		= 'strpart(getline("."), 0, col(".") - 1) =~ ''\\\@<!%'''
	    let stopline 	= search('^\s*$\|\\par\>', 'bnW')

	    " Check Brackets 
	    let b:comp_method   .= " brackets: 1"
	    let cl_return 	= atplib#complete#GetBracket(append, g:atp_bracket_dict)

	    " If the bracket was closed return.
	    if cl_return != "0"
	        let g:time_TabCompletion=reltimestr(reltime(time))
		return cl_return
	    endif

	    " Check inline math:
	    if atplib#complete#CheckClosed_math('texMathZoneV') || 
			\ atplib#complete#CheckClosed_math('texMathZoneW') ||
			\ atplib#complete#CheckClosed_math('texMathZoneX') ||
			\ b:atp_TexFlavor == 'plaintex' && atplib#complete#CheckClosed_math('texMathZoneY')
		let zone = 'texMathZoneVWXY' 	" DEBUG
		call atplib#complete#CloseLastEnvironment(append, 'math')

	    " Check environments:
	    else
		let env_opened= searchpairpos('\\begin','','\\end','bnW','searchpair("\\\\begin{".matchstr(getline("."),"\\\\begin{\\zs[^}]*\\ze}"),"","\\\\end{".matchstr(getline("."),"\\\\begin{\\zs[^}]*\\ze}"),"nW")',max([1,(line(".")-g:atp_completion_limits[2])]))
		let env_name 	= matchstr(strpart(getline(env_opened[0]), env_opened[1]-1), '\\begin\s*{\zs[^}]*\ze}')
		let zone	= env_name 	" DEBUG
		if env_opened != [0, 0]
		    call atplib#complete#CloseLastEnvironment('a', 'environment', env_name, env_opened)
		endif
	    endif
	    " DEBUG
	    if exists("zone")
		let b:tc_return =" close_env end " . zone
		let b:comp_method.=' close_env end ' . zone
		call atplib#Log("TabCompletion.log", "b:comp_method.=".b:comp_method)
	    else
		let b:tc_return=" close_env end"
		let b:comp_method.=' close_env end'
		call atplib#Log("TabCompletion.log", "b:comp_method=".b:comp_method)
	    endif
	elseif len == 0 && 
		    \ completion_method != 'labels' && 
		    \ completion_method != 'bibitems' 
		    \ || len == 1 && get(completions, 0, "") == matched_word || 
		    \ completion_method != 'brackets' &&
		    \ completion_method != 'labels' &&
		    \ completion_method != 'bibitems' &&
		    \ completion_method != 'bibfiles' &&
		    \ completion_method != 'close environments' &&
		    \ completion_method != 'algorithmic' &&
		    \ completion_method != 'abbreviations' &&
		    \ completion_method != 'command' &&
		    \ completion_method != 'command values' &&
		    \ completion_method != 'tikzpicture' &&
		    \ completion_method != 'tikzpicture commands' &&
		    \ completion_method != 'tikzpicture keywords' &&
		    \ completion_method != 'package options' &&
		    \ completion_method != 'documentclass' &&
		    \ completion_method != 'documentclass options' &&
		    \ completion_method != 'environment_names' &&
		    \ completion_method != 'environment options' &&
		    \ completion_method != 'todo options' &&
		    \ completion_method != 'missingfigure options'
" 	elseif completion_method == 'package' || 
" 		    \  completion_method == 'environment_names' || 
" 		    \  completion_method == 'font encoding' || 
" 		    \  completion_method == 'font family' || 
" 		    \  completion_method == 'font series' || 
" 		    \  completion_method == 'font shape' || 
" 		    \  completion_method == 'bibstyles' || 
" 		    \ completion_method == 'bibfiles'
	    let b:tc_return='close_bracket end'
	    let b:comp_method .= " brackets: 2"
	    let g:time_TabCompletion=reltimestr(reltime(time))
	    return atplib#complete#GetBracket(append, g:atp_bracket_dict)
	endif
    endif
    "}}}3
    let g:time_TabCompletion=reltimestr(reltime(time))
    return ''
    "}}}2
endfunction
catch /E127:/
endtry
" }}}1
" vim:fdm=marker:ff=unix:noet:ts=8:sw=4:fdc=1
autoload/atplib/fontpreview.vim	[[[1
433
" Title: 	Vim library for ATP filetype plugin.
" Author:	Marcin Szamotulski
" Email:	mszamot [AT] gmail [DOT] com
" Note:		This file is a part of Automatic Tex Plugin for Vim.
" URL:		https://launchpad.net/automatictexplugin
" Language:	tex

" Font Preview Functions:
" These functions search for fd files and show them in a buffer with filetype
" 'fd_atp'. There are additional function for this filetype written in
" fd_atp.vim ftplugin. Distributed with atp.
"{{{1 atplib#fontpreview#FdSearch
"([<pattern>,<method>])
" There are two methods: 
" 	0 - match fd file names ( ":t" filename modifier)        <- the default one
" 	1 - match fd file path 
function! atplib#fontpreview#FdSearch(...)

    if a:0 == 0
	let pattern	= ""
	let method	= 0
    else
	let pattern	= ( a:0 >= 1 ? a:1 : "" )
	let method	= ( a:0 >= 2 ? a:2 : 0 )
    endif

"     let g:method = method
"     let g:pattern = pattern

    " Find fd file
    let path	= substitute(substitute(system("kpsewhich -show-path tex"),'!!','','g'),'\/\/\+','\/','g')
    let path	= substitute(path,':\|\n',',','g')
    let fd 	= split(globpath(path,"**/*.fd"),'\n') 

    let g:fd	= copy(fd)

    " Match for l:pattern
    let fd_matches=[]
    if method == 0
	call filter(fd, 'fnamemodify(v:val, ":t") =~ pattern') 
    else
	call filter(fd, 'v:val =~ pattern') 
    endif

    return fd
endfunction
"{{{1 atplib#fontpreview#FontSearch
" atplib#fontpreview#FontSearch(method,[<pattern>]) 
" method = "" match for name of fd file
" method = "!" match against whole path
function! atplib#fontpreview#FontSearch(method,...)
	
    let l:method	= ( a:method == "!" ? 1 : 0 )
    let l:pattern	= ( a:0 ? a:1 : "" )

    let s:fd_matches=atplib#fontpreview#FdSearch(l:pattern, l:method)

    " Open Buffer and list fd files
    " set filetype to fd_atp
    let l:tmp_dir=tempname()
    call mkdir(l:tmp_dir)
    let l:fd_bufname="fd_list " . l:pattern
    let l:openbuffer="32vsplit! +setl\\ nospell\\ ft=fd_atp ". fnameescape(l:tmp_dir . "/" . l:fd_bufname )

    let g:fd_matches=[]
    if len(s:fd_matches) > 0
	echohl WarningMsg
	echomsg "[ATP:] found " . len(s:fd_matches) . " files."
	echohl None
	" wipe out the old buffer and open new one instead
	if buflisted(fnameescape(l:tmp_dir . "/" . l:fd_bufname))
	    silent exe "bd! " . bufnr(fnameescape(l:tmp_dir . "/" . l:fd_bufname))
	endif
	silent exe l:openbuffer
	" make l:tmp_dir available for this buffer.
" 	let b:tmp_dir=l:tmp_dir
	cd /tmp
	map <buffer> q	:bd<CR>

	" print the lines into the buffer
	let l:i=0
	call setline(1,"FONT DEFINITION FILES:")
	for l:fd_file in s:fd_matches
	    " we put in line the last directory/fd_filename:
	    " this is what we cut:
	    let l:path=fnamemodify(l:fd_file,":h:h")
	    let l:fd_name=substitute(l:fd_file,"^" . l:path . '/\?','','')
" 	    call setline(line('$')+1,fnamemodify(l:fd_file,":t"))
	    call setline(line('$')+1,l:fd_name)
	    call add(g:fd_matches,l:fd_file)
	    let l:i+=1
	endfor
	call append('$', ['', 'maps:', 
			\ 'p       Preview font ', 
			\ 'P       Preview font+tex file', 
			\ '<Tab>   Show Fonts in fd file', 
			\ '<Enter> Open fd file', 
			\ 'q       "bd!"',
			\ '',
			\ 'Note: p/P works in visual mode'])
	silent w
	setlocal nomodifiable
	setlocal ro
    else
	echohl WarningMsg
	if !l:method
	    echomsg "[ATP:] no fd file found, try :FontSearch!"
	else
	    echomsg "[ATP:] no fd file found."
	endif
	echohl None
    endif

endfunction
"{{{1 atplib#fontpreview#Fd_completion /not needed/
" if !exists("*atplib#Fd_completion")
" function! atplib#fontpreview#Fd_completion(A,C,P)
"     	
"     " Find all files
"     let l:path=substitute(substitute(system("kpsewhich -show-path tex"),'!!','','g'),'\/\/\+','\/','g')
"     let l:path=substitute(l:path,':\|\n',',','g')
"     let l:fd=split(globpath(l:path,"**/*.fd"),"\n") 
"     let l:fd=map(l:fd,'fnamemodify(v:val,":t:r")')
" 
"     let l:matches=[]
"     for l:fd_file in l:fd
" 	if l:fd_file =~ a:A
" 	    call add(l:matches,l:fd_file)
" 	endif
"     endfor
"     return l:matches
" endfunction
" endif
" {{{1 atplib#fontpreview#OpenFdFile /not working && not needed?/
" function! atplib#fontpreview#OpenFdFile(name)
"     let l:path=substitute(substitute(system("kpsewhich -show-path tex"),'!!','','g'),'\/\/\+','\/','g')
"     let l:path=substitute(l:path,':\|\n',',','g')
"     let b:path=l:path
"     let l:fd=split(globpath(l:path,"**/".a:name.".fd"),"\n") 
"     let l:fd=map(l:fd,'fnamemodify(v:val,":t:r")')
"     let b:fd=l:fd
"     execute "split +setl\\ ft=fd_atp " . l:fd[0]
" endfunction
"{{{1 atplib#fontpreview#Preview
" keep_tex=1 open the tex file of the sample file, otherwise it is deleted (at
" least from the buffer list).
" To Do: fd_file could be a list of fd_files which we would like to see, every
" font should be done after \pagebreak[4]
" if a:fd_files=['buffer'] it means read the current buffer (if one has opened
" an fd file).
function! atplib#fontpreview#Preview(fd_files,keep_tex)
    if a:fd_files != ["buffer"]
	let l:fd_files={}
	for l:fd_file in a:fd_files
	    call extend(l:fd_files,{fd_file : readfile(l:fd_file)})
	endfor
    else
	let l:fd_files={bufname("%"):getline(1,"$")}
    endif
    unlet l:fd_file

    let l:declare_command='\C\%(DeclareFontShape\%(WithSizes\)\?\|sauter@\%(tt\)\?family\|EC@\%(tt\)\?family\|krntstexmplfamily\|HFO@\%(tt\)\?family\)'
    let b:declare_command=l:declare_command
    
    let l:font_decl_dict={}
    for l:fd_file in a:fd_files
	call extend(l:font_decl_dict, {l:fd_file : [ ]})
	for l:line in l:fd_files[l:fd_file]
	    if l:line =~ '\\'.l:declare_command.'\s*{[^#}]*}\s*{[^#}]*}\s*{[^#}]*}\s*{[^#}]*}'
		call add(l:font_decl_dict[l:fd_file],l:line)
	    endif
	endfor
    endfor

    let l:tmp_dir=tempname()
    call mkdir(expand(l:tmp_dir))
    if a:fd_files == ["buffer"]
	" WINDOWS NOT COMPATIBLE
	let l:testfont_file=l:tmp_dir . "/" . fnamemodify(bufname("%"),":t:r") . ".tex"
    else
	" the name could be taken from the pattern
	" or join(map(keys(deepcopy(a:fd_files)),'substitute(fnamemodify(v:val,":t:r"),".fd$","","")'),'_')
	" though it can be quite a long name.
	let l:testfont_file=l:tmp_dir . "/" . fnamemodify(a:fd_files[0],":t:r") . ".tex"
    endif
    " WINDOWS NOT COMPATIBLE
"     call system("touch " . l:testfont_file)
    
    let l:fd_bufnr=bufnr("%")

    let s:text="On November 14, 1885, Senator \\& Mrs.~Leland Stanford called
		\ together at their San Francisco mansion the 24~prominent men who had
		\ been chosen as the first trustees of The Leland Stanford Junior University.
		\ They handed to the board the Founding Grant of the University, which they
		\ had executed three days before.\\\\
		\ (!`THE DAZED BROWN FOX QUICKLY GAVE 12345--67890 JUMPS!)"

"     let l:text="On November 14, 1885, Senator \\& Mrs.~Leland Stanford called
" 	\ together at their San Francisco mansion the 24~prominent men who had
" 	\ been chosen as the first trustees of The Leland Stanford Junior University.
" 	\ They handed to the board the Founding Grant of the University, which they
" 	\ had executed three days before. This document---with various amendments,
" 	\ legislative acts, and court decrees---remains as the University's charter.
" 	\ In bold, sweeping language it stipulates that the objectives of the University
" 	\ are ``to qualify students for personal success and direct usefulness in life;
" 	\ and to promote the public welfare by exercising an influence in behalf of
" 	\ humanity and civilization, teaching the blessings of liberty regulated by
" 	\ law, and inculcating love and reverence for the great principles of
" 	\ government as derived from the inalienable rights of man to life, liberty,
" 	\ and the pursuit of happiness.''\\
" 	\ (!`THE DAZED BROWN FOX QUICKLY GAVE 12345--67890 JUMPS!)\\par}}
" 	\ \\def\\\moretext{?`But aren't Kafka's Schlo{\\ss} and {\\AE}sop's {\\OE}uvres
" 	\ often na{\\"\\i}ve  vis-\\`a-vis the d{\\ae}monic ph{\\oe}nix's official r\\^ole
" 	\ in fluffy souffl\\'es? }
" 	\ \\moretext"

    if a:fd_files == ["buffer"]
	let l:openbuffer="edit "
    else
	let l:openbuffer="topleft split!"
    endif
    execute l:openbuffer . " +setlocal\\ ft=tex\\ modifiable\\ noro " . l:testfont_file 
    " Clear the file (if one has a skeleton file it will be removed.)
    normal! ggdG
    let b:atp_ProjectScript = 0
    map <buffer> q :bd!<CR>

    call setline(1,'\documentclass{article}')
    call setline(2,'\oddsidemargin=0pt')
    call setline(3,'\textwidth=450pt')
    call setline(4,'\textheight=700pt')
    call setline(5,'\topmargin=-10pt')
    call setline(6,'\headsep=0pt')
    call setline(7,'\begin{document}')

    let l:i=8
    let l:j=1
    let l:len_font_decl_dict=len(l:font_decl_dict)
    let b:len_font_decl_dict=l:len_font_decl_dict
    for l:fd_file in keys(l:font_decl_dict) 
	if l:j == 1 
	    call setline(l:i,'\textsc\textbf{\Large Fonts from the file '.l:fd_file.'}\\[2em]')
	    let l:i+=1
	else
" 	    call setline(l:i,'\pagebreak[4]')
	    call setline(l:i,'\vspace{4em}')
	    call setline(l:i+1,'')
	    call setline(l:i+2,'\textsc\textbf{\Large Fonts from the file '.l:fd_file.'}\\[2em]')
	    let l:i+=3
	endif
	let l:len_font_decl=len(l:font_decl_dict[l:fd_file])
	let b:match=[]
	for l:font in l:font_decl_dict[l:fd_file]
	    " SHOW THE FONT ENCODING, FAMILY, SERIES and SHAPE
	    if matchstr(l:font,'\\'.l:declare_command.'\s*{[^#}]*}\s*{[^#}]*}\s*{\zs[^#}]*\ze}\s*{[^#}]*}') == "b" ||
			\ matchstr(l:font,'\\'.l:declare_command.'\s*{[^#}]*}\s*{[^#}]*}\s*{\zs[^#}]*\ze}\s*{[^#}]*}') == "bx"
		let b:show_font='\noindent{\large \textit{Font Encoding}: \textsf{' . 
			    \ matchstr(l:font,'\\'.l:declare_command.'\s*{\zs[^#}]*\ze}\s*{[^#}]*}\s*{[^#}]*}\s*{[^#}]*}') . '}' . 
			    \ ' \textit{Font Family}: \textsf{' .  
			    \ matchstr(l:font,'\\'.l:declare_command.'\s*{[^}#]*}\s*{\zs[^#}]*\ze}\s*{[^#}]*}\s*{[^#}]*}') . '}' . 
			    \ ' \textit{Font Series}: \textsf{' .  
			    \ matchstr(l:font,'\\'.l:declare_command.'\s*{[^#}]*}\s*{[^#}]*}\s*{\zs[^#}]*\ze}\s*{[^#}]*}') . '}' . 
			    \ ' \textit{Font Shape}: \textsf{' .  
			    \ matchstr(l:font,'\\'.l:declare_command.'\s*{[^#}]*}\s*{[^#}]*}\s*{[^#}]*}\s*{\zs[^#}]*\ze}') . '}}\\[2pt]'
	    else
		let b:show_font='\noindent{\large \textbf{Font Encoding}: \textsf{' . 
			    \ matchstr(l:font,'\\'.l:declare_command.'\s*{\zs[^#}]*\ze}\s*{[^#}]*}\s*{[^#}]*}\s*{[^#}]*}') . '}' . 
			    \ ' \textbf{Font Family}: \textsf{' .  
			    \ matchstr(l:font,'\\'.l:declare_command.'\s*{[^}#]*}\s*{\zs[^#}]*\ze}\s*{[^#}]*}\s*{[^#}]*}') . '}' . 
			    \ ' \textbf{Font Series}: \textsf{' .  
			    \ matchstr(l:font,'\\'.l:declare_command.'\s*{[^#}]*}\s*{[^#}]*}\s*{\zs[^#}]*\ze}\s*{[^#}]*}') . '}' . 
			    \ ' \textbf{Font Shape}: \textsf{' .  
			    \ matchstr(l:font,'\\'.l:declare_command.'\s*{[^#}]*}\s*{[^#}]*}\s*{[^#}]*}\s*{\zs[^#}]*\ze}') . '}}\\[2pt]'
	    endif
	    call setline(l:i,b:show_font)
	    let l:i+=1
	    " CHANGE THE FONT
	    call setline(l:i,'{' . substitute(
			\ matchstr(l:font,'\\'.l:declare_command.'\s*{[^#}]*}\s*{[^#}]*}\s*{[^#}]*}\s*{[^#}]*}'),
			\ l:declare_command,'usefont','') . 
			\ '\selectfont')
	    " WRITE SAMPLE TEXT
	    call add(b:match,matchstr(l:font,'\\'.l:declare_command.'\s*{[^#}]*}\s*{[^#}]*}\s*{[^#}]*}\s*{[^#}]*}'))
	    let l:i+=1
	    " END
	    if l:j<l:len_font_decl
		call setline(l:i,s:text . '}\\\\')
	    else
		call setline(l:i,s:text . '}')
	    endif
	    let l:i+=1
	    let l:j+=1
	endfor
    endfor
    call setline(l:i,'\end{document}')
    normal! gg
    silent w
    if b:atp_TexCompiler =~ '^pdf'	
	let l:ext=".pdf"
    else
	let l:ext=".dvi"
    endif
    call system(b:atp_TexCompiler . " " . l:testfont_file . 
	    \ " && " . b:atp_Viewer . " " . fnamemodify(l:testfont_file,":p:r") . l:ext ." &")
    if !a:keep_tex
	silent exe "bd"
    endif
endfunction
"{{{1 atplib#fontpreview#FontPreview
" a:fd_file  pattern to find fd file (.fd will be appended if it is not
" present at the end),
" a:1 = encoding
" a:2 = l:keep_tex, i.e. show the tex source.
function! atplib#fontpreview#FontPreview(method, fd_file,...)


    let l:method	= ( a:method == "!" ? 1 : 0 )
    let l:enc		= ( a:0 >= 1 ? a:1 : "" )
    let l:keep_tex 	= ( a:0 >= 2 ? a:2 : 0 )

    if filereadable(a:fd_file)
	let l:fd_file=a:fd_file
    else
	" Find fd file
	if a:fd_file !~ '.fd\s*$'
	    let l:fd_file=a:fd_file.".*.fd"
	else
	    let l:fd_file=a:fd_file
	endif

	let l:fd=atplib#fontpreview#FdSearch(a:fd_file, l:method)
	let g:fd=l:fd
	if !empty(l:enc)
	    call filter(l:fd, "fnamemodify(v:val, ':t') =~ '^' . l:enc")
	endif

	if len(l:fd) == 0
	    if !l:method
		echo "FD file not found. Try :FontPreview!"
	    else
		echo "FD file not found."
	    endif
	    return
	elseif len(l:fd) == 1
	    let l:fd_file_list=l:fd
	else
	    let l:i=1
	    for l:f in l:fd
		echo l:i." ".substitute(f,'^'.fnamemodify(f,":h:h").'/\?','','')
		let l:i+=1
	    endfor
	    let l:choice=input('Which fd file? ')
	    if l:choice == "" 
		return
	    endif
	    let l:choice_list=split(l:choice,',')
	    let b:choice_list=l:choice_list
	    " if there is 1-4  --> a list of 1,2,3,4
	    let l:new_choice_list=[]
	    for l:ch in l:choice_list
		if l:ch =~ '^\d\+$'
		    call add(l:new_choice_list,l:ch)
		elseif l:ch =~ '^\d\+\s*-\s*\d\+$'
		    let l:b=matchstr(l:ch,'^\d\+')
		    let l:e=matchstr(l:ch,'\d\+$')
		    let l:k=l:b
		    while l:k<=l:e
			call add(l:new_choice_list,l:k)
			let l:k+=1
		    endwhile
		endif
	    endfor
	    let b:new_choice_list=l:new_choice_list
	    let l:fd_file_list=map(copy(l:new_choice_list),'get(l:fd,(v:val-1),"")')
	    let l:fd_file_list=filter(l:fd_file_list,'v:val != ""')
" 	    let l:fd_file=get(l:fd,l:choice-1,"return")
	    if len(l:fd_file_list) == 0
		return
	    endif
	endif
    endif
    call atplib#fontpreview#Preview(l:fd_file_list,l:keep_tex)
endfunction
" {{{1 atplib#fontpreview#ShowFonts
function! atplib#fontpreview#ShowFonts_vim(fd_file)
    let l:declare_command='\C\%(DeclareFontShape\%(WithSizes\)\?\|sauter@\%(tt\)\?family\|EC@\%(tt\)\?family\|krntstexmplfamily\|HFO@\%(tt\)\?family\)'
    
    let l:font_decl=[]
    for l:line in readfile(a:fd_file)
	if l:line =~ '\\'.l:declare_command.'\s*{[^#}]*}\s*{[^#}]*}\s*{[^#}]*}\s*{[^#}]*}'
	    call add(l:font_decl,l:line)
	endif
    endfor
    let l:font_commands=[]
    for l:font in l:font_decl
	call add(l:font_commands,substitute(
		    \ matchstr(l:font,'\\'.l:declare_command.'\s*{[^#}]*}\s*{[^#}]*}\s*{[^#}]*}\s*{[^#}]*}'),
		    \ l:declare_command,'usefont',''))
    endfor
    return l:font_commands
endfunction
function! atplib#fontpreview#ShowFonts_py(fd_file)
python << END
import vim, re
file=vim.eval("a:fd_file")
try:
    file_o=open(file, "r")
    file_l=file_o.readlines()
    declare_pat=re.compile('(?:DeclareFontShape(?:WithSizes)?|sauter@(?:tt)?family|EC@(?:tt)?family|krntstexmplfamily|HFO@(?:tt)?family)')
    font_pat=re.compile('(\\\\(?:DeclareFontShape(?:WithSizes)?|sauter@(?:tt)?family|EC@(?:tt)?family|krntstexmplfamily|HFO@(?:tt)?family)\s*{[^#}]*}\s*{[^#}]*}\s*{[^#}]*}\s*{[^#}]*})')
    font_commands=[]
    for line in file_l:
        if re.search(declare_pat, line):
            font_cmd=re.search(font_pat, line)
            if font_cmd:
                font=font_cmd.group(0)
                font=re.sub(declare_pat, 'usefont', font)
                font_commands.append(font)
        vim.command("let s:return_ShowFonts_py="+str(font_commands))
except IOError:
    vim.command("let s:return_ShowFonts_py=[]")
END
return map(s:return_ShowFonts_py, "substitute(v:val, '^\\', '', '')")
endfunction
function! atplib#fontpreview#ShowFonts(fd_file)
    if has("python")
        return atplib#fontpreview#ShowFonts_py(a:fd_file)
    else
        return atplib#fontpreview#ShowFonts(a:fd_file)
    endif
endfunction
" }}}1
" vim:fdm=marker:ff=unix:noet:ts=8:sw=4:fdc=1
autoload/atplib/helpfunctions.vim	[[[1
212
" Author: 	Marcin Szamotulski
" Description: 	This file contains help commands and variables (for mappings used by ATP) 
" Note:		This file is a part of Automatic Tex Plugin for Vim.
" Language:	tex
" Last Change:

" {{{1 Help Math IMAPS
function! atplib#helpfunctions#HelpMathIMaps()

    if exists("g:no_plugin_maps") || exists("g:no_atp_maps")
	echomsg "[ATP:] ATP maps are turned off"
	return ''
    endif

    let g:help_mathimaps = ''
	\."\n MATH IMAPS"
	\."\n <maplocalleader> has value g:atp_imap_leader_1"
	\."\n ".g:atp_imap_leader_1."a \\alpha            ".g:atp_imap_leader_1."b \\beta"
	\."\n ".g:atp_imap_leader_1."g \\gamma            ".g:atp_imap_leader_1."d \\delta"
	\."\n ".g:atp_imap_leader_1."e \\epsilon          ".g:atp_imap_leader_1."ve \\varepsilon"
	\."\n ".g:atp_imap_leader_1."z \\zeta             ".g:atp_imap_leader_1."h \\eta"
	\."\n ".g:atp_imap_leader_1."o \\theta            ".g:atp_imap_leader_1."vo \\vartheta"
	\."\n ".g:atp_imap_leader_1."i \\iota             ".g:atp_imap_leader_1."k \\kappa"
	\."\n ".g:atp_imap_leader_1."l \\lambda           ".g:atp_imap_leader_1."m \\mu"
	\."\n ".g:atp_imap_leader_1."n \\nu               ".g:atp_imap_leader_1."x \\xi"
	\."\n ".g:atp_imap_leader_1."p \\pi               ".g:atp_imap_leader_1."r \\rho"
	\."\n ".g:atp_imap_leader_1."s \\sigma            ".g:atp_imap_leader_1."vs \\varsigma" 
	\."\n ".g:atp_imap_leader_1."t \\tau              ".g:atp_imap_leader_1."u \\upsilon"
	\."\n ".g:atp_imap_leader_1."f \\phi              ".g:atp_imap_leader_1."c \\chi"
	\."\n ".g:atp_imap_leader_1."y \\psi              ".g:atp_imap_leader_1."w \\omega"
	\."\n"
	\."\n ".g:atp_imap_leader_1."G \\Gamma            ".g:atp_imap_leader_1."D \\Delta"
	\."\n ".g:atp_imap_leader_1."Z \\mathrm{Z}        ".g:atp_imap_leader_1."O \\Theta"
	\."\n ".g:atp_imap_leader_1."L \\Lambda           ".g:atp_imap_leader_1."M \\Mu"
	\."\n ".g:atp_imap_leader_1."N \\Nu               ".g:atp_imap_leader_1."P \\Pi"
	\."\n ".g:atp_imap_leader_1."S \\Sigma            ".g:atp_imap_leader_1."U \\Upsilon"
	\."\n ".g:atp_imap_leader_1."F \\Phi              ".g:atp_imap_leader_1."Y \\Psi"
	\."\n ".g:atp_imap_leader_1."W \\Omega"
	\."\n"
	\."\n ".g:atp_imap_leader_1."+ \\bigcup           ".g:atp_imap_leader_1."- \\setminus" 
	\."\n ".g:atp_infty_leader."8 \\infty            ".g:atp_imap_leader_1."& \\wedge"
	\."\n ".                        "^^ ^{}               ".                        "__ _{}"
	\."\n ".g:atp_imap_leader_3."m \\(\\)              ".g:atp_imap_leader_3."M \\[\\]           <maplocalleader> has value g:atp_imap_leader_3" 
    return g:help_mathimaps
endfunction
silent call atplib#helpfunctions#HelpMathIMaps()

" {{{1 Help Environment IMAPS
function! atplib#helpfunctions#HelpEnvIMaps()

    if exists("g:no_plugin_maps") || exists("g:no_atp_maps")
	echomsg "[ATP:] ATP maps are turned off"
	return ''
    endif

    let g:help_envimaps = ''
		\."\n ENVIRONMENT IMAPS" 
		\."\n <maplocalleader> has value g:atp_imap_leader_3"
		\."\n ".(g:atp_imap_begin != "" ? g:atp_imap_leader_3.g:atp_imap_begin." \\begin{}             " : "" ).(g:atp_imap_end != "" ? g:atp_imap_leader_3.g:atp_imap_end." \\end{}" : "")
		\."\n ".(g:atp_imap_theorem != "" ? g:atp_imap_leader_3.g:atp_imap_theorem." theorem              " : "" ).(g:atp_imap_definition != "" ? g:atp_imap_leader_3.g:atp_imap_definition." definition" : "")
		\."\n ".(g:atp_imap_proposition != "" ? g:atp_imap_leader_3.g:atp_imap_proposition." proposition          " : "").(g:atp_imap_lemma != "" ? g:atp_imap_leader_3.g:atp_imap_lemma." lemma" : "")
		\."\n ".(g:atp_imap_remark != "" ? g:atp_imap_leader_3.g:atp_imap_remark." remark               " : "").(g:atp_imap_corollary != "" ? g:atp_imap_leader_3.g:atp_imap_corollary." corollary" : "")
		\."\n ".(g:atp_imap_proof != "" ? g:atp_imap_leader_3.g:atp_imap_proof." proof                " : "").(g:atp_imap_example != "" ? g:atp_imap_leader_3.g:atp_imap_example." example" : "")
		\."\n ".(g:atp_imap_note != "" ? g:atp_imap_leader_3.g:atp_imap_note." note                 " : "")
		\."\n"
		\."\n ".(g:atp_imap_enumerate != "" ? g:atp_imap_leader_3.g:atp_imap_enumerate." enumerate            " : "").(g:atp_imap_itemize != "" ? g:atp_imap_leader_3.g:atp_imap_itemize." itemize" : "")
		\."\n ".(g:atp_imap_item != "" ? g:atp_imap_leader_3.g:atp_imap_item." \\item" : "")
		\."\n"
		\.(g:atp_imap_align != "" ? "\n ".g:atp_imap_leader_3.g:atp_imap_align." align                " : "").(g:atp_imap_equation != "" ? g:atp_imap_leader_3.g:atp_imap_equation." equation" : "")
		\."\n"
		\."\n ".(g:atp_imap_flushleft != "" ? g:atp_imap_leader_3.g:atp_imap_flushleft." flushleft            " : "").(g:atp_imap_flushright != "" ? g:atp_imap_leader_3.g:atp_imap_flushright." flushright" : "")
		\."\n ".(g:atp_imap_center != "" ? g:atp_imap_leader_3.g:atp_imap_center." center" : "")
		\."\n"
		\.(g:atp_imap_tikzpicture != "" ? "\n ".g:atp_imap_leader_3.g:atp_imap_tikzpicture." tikzpicture" : "")
		\."\n"
		\."\n ".(g:atp_imap_frame != "" ? g:atp_imap_leader_3.g:atp_imap_frame." frame                " : "").(g:atp_imap_letter != "" ?  g:atp_imap_leader_3.g:atp_imap_letter." letter" : "" )
    return g:help_envimaps
endfunction

" {{{1 Help VMaps
function! atplib#helpfunctions#HelpVMaps() 

    if exists("g:no_plugin_maps") || exists("g:no_atp_maps")
	echomsg "[ATP:] ATP maps are turned off"
	return ''
    endif

    let l:atp_vmap_text_font_leader 	= ( exists("maplocalleader") && g:atp_vmap_text_font_leader 	== "<LocalLeader>" ? maplocalleader : g:atp_vmap_text_font_leader )
    let l:atp_vmap_environment_leader 	= ( exists("maplocalleader") && g:atp_vmap_environment_leader 	== "<LocalLeader>" ? maplocalleader : g:atp_vmap_environment_leader )
    let l:atp_vmap_bracket_leader 	= ( exists("maplocalleader") && g:atp_vmap_bracket_leader 	== "<LocalLeader>" ? maplocalleader : g:atp_vmap_bracket_leader )
    let l:atp_vmap_big_bracket_leader 	= ( exists("maplocalleader") && g:atp_vmap_big_bracket_leader 	=~ "<LocalLeader>" ? substitute(g:atp_vmap_big_bracket_leader, '<LocalLeader>', maplocalleader, '')  : g:atp_vmap_big_bracket_leader )

    let g:help_vmaps = ''
	    \."\n <maplocalleader> has value g:atp_vmap_text_font_leader"
	    \."\n KEYMAP            TEXT MODE            MATH MODE"
	    \."\n ".l:atp_vmap_text_font_leader."rm               \\textrm{}            \\mathrm{}"
	    \."\n ".l:atp_vmap_text_font_leader."em               \\emph{}              \\mathit{}"
	    \."\n ".l:atp_vmap_text_font_leader."it               \\textit{}            \\mathit{}"
	    \."\n ".l:atp_vmap_text_font_leader."sf               \\textsf{}            \\mathsf{}"
	    \."\n ".l:atp_vmap_text_font_leader."tt               \\texttt{}            \\mathtt{}"
	    \."\n ".l:atp_vmap_text_font_leader."bf               \\textbf{}            \\mathbf{}"
	    \."\n ".l:atp_vmap_text_font_leader."bb               \\textbf{}            \\mathbb{}"
	    \."\n ".l:atp_vmap_text_font_leader."bb               \\textbf{}            \\mathbb{}"
	    \."\n ".l:atp_vmap_text_font_leader."sl               \\textsl{}"
	    \."\n ".l:atp_vmap_text_font_leader."sc               \\textsc{}"
	    \."\n ".l:atp_vmap_text_font_leader."up               \\textup{}"
	    \."\n ".l:atp_vmap_text_font_leader."md               \\textmd{}"
	    \."\n ".l:atp_vmap_text_font_leader."un               \\underline{}         \\underline{}"
	    \."\n ".l:atp_vmap_text_font_leader."ov               \\overline{}          \\overline{}"
	    \."\n ".l:atp_vmap_text_font_leader."no               \\textnormal{}        \\mathnormal{}"
	    \."\n ".l:atp_vmap_text_font_leader."cal                                   \\mathcal{}"
	    \."\n "
	    \."\n MODE INDEPENDENT VMAPS:"
	    \."\n <maplocalleader> has value g:atp_vmap_environment_leader"
	    \."\n ".l:atp_vmap_environment_leader."C		   wrap in center environment"
	    \."\n ".l:atp_vmap_environment_leader."L		   wrap in flushleft environment"
	    \."\n ".l:atp_vmap_environment_leader."R		   wrap in flushright environment"
	    \."\n ".l:atp_vmap_environment_leader."E		   wrap in equation environment"
	    \."\n ".l:atp_vmap_environment_leader."A		   wrap in align environment"
	    \."\n "
	    \."\n <maplocalleader> has value g:atp_vmap_bracket_leader"
	    \."\n ".l:atp_vmap_bracket_leader."(                (:)            ".l:atp_vmap_bracket_leader.")           (:)" 
	    \."\n ".l:atp_vmap_bracket_leader."[                [:]            ".l:atp_vmap_bracket_leader."]           [:]" 
	    \."\n ".l:atp_vmap_bracket_leader."{                {:}            ".l:atp_vmap_bracket_leader."}           {:}" 
	    \."\n ".l:atp_vmap_bracket_leader."\\{              \\{:\\}           ".l:atp_vmap_bracket_leader."\\}         \\{:\\}" 
	    \."\n m                \\(:\\)           M           \\[:\\] "
	    \."\n "
	    \."\n <maplocalleader> has value g:atp_vmap_big_bracket_leader"
	    \."\n ".l:atp_vmap_big_bracket_leader."(          \\left(:\\right)      ".l:atp_vmap_big_bracket_leader.")     \\left(:\\right)" 
	    \."\n ".l:atp_vmap_big_bracket_leader."[          \\left[:\\right]      ".l:atp_vmap_big_bracket_leader."]     \\left[:\\right]" 
	    \."\n ".l:atp_vmap_big_bracket_leader."{          \\left{:\\right}      ".l:atp_vmap_big_bracket_leader."}     \\left{:\\right}" 
	    \."\n ".l:atp_vmap_big_bracket_leader."\\{        \\left\\{:\\right\\}     ".l:atp_vmap_big_bracket_leader."\\}   \\left\\{:\\right\\}" 
	    \."\n "
	    \."\n ".l:atp_vmap_text_font_leader."f                \\usefont{".g:atp_font_encoding."}{}{}{}\\selectfont" 
    return g:help_vmaps 
endfunction
" {{{1 Help IMaps
" function! atplib#helpfunctions#HelpIMaps()
" let tc_imap = maparg("<Tab>  ", 'i') =~# 'atplib#complete#TabCompletion' ? '<Tab>' : 
" 	    \ maparg("<F7>   ", 'i') =~# 'atplib#complete#TabCompletion' ? '<F7>' : ""
" let netc_imap = tc_imap == "<Tab>" ? "<S-Tab>" : tc_imap == "<F7>" ? "<S-F7>" : ""
"     let g:help_imaps = ''
" 	    \."\n <maplocalleader> has value g:atp_vmap_text_font_leader"
" 	    \."\n ".tc_imap."            "."Completion (expert mode)"
" 	    \."\n ".netc_imap."            "."Completion (non-expert mode)"
" endfunction
" silent call atplib#helpfunctions#HelpIMaps()
" command! -buffer HelpIMaps :echo atplib#helpfunctions#HelpIMaps()
" }}}1
" {{{1 MapSearch
function! atplib#helpfunctions#MapSearch(bang,rhs_pattern,...)
    let mode = ( a:0 >= 1 ? a:1 : '' )
    let more = &more
    setl nomore
    redir => maps
	exe "silent ".mode."map"
    redir end
    let &l:more = more
    let list = split(maps, "\n")
    let pure_rhs_list = map(copy(list), 'matchstr(v:val, ''.\s\+\S\+\s\+\zs.*'')')
    let rhs_list  = ( a:bang == "" ?  copy(pure_rhs_list) :
		\ map(copy(list), 'matchstr(v:val, ''.\s\+\zs\S\+\s\+.*'')') )
    if mode == 'i'
	let j=0
	for entry in g:atp_imap_greek_letters
		    \ +g:atp_imap_math_misc
		    \ +g:atp_imap_diacritics
		    \ +g:atp_imap_environments
		    \ +g:atp_imap_math
		    \ +g:atp_imap_fonts 
	    let entry_tab = substitute(entry[4], "\t", '<Tab>', 'g')
	    let entry_tab = substitute(entry_tab, "", '<C-R>', 'g')
	    if index(pure_rhs_list, entry_tab)	== -1 &&
			\ index(pure_rhs_list, "*".entry_tab) == -1 &&
			\ index(pure_rhs_list, "@".entry_tab) == -1 &&
			\ index(pure_rhs_list, "*@".entry_tab) == -1 
		" Debug:
		    let j+=1
		let space = join(map(range(max([12-len(entry[2].entry[3]),1])), "' '"), "")
		call add(list, 'i  '.entry[2].entry[3].space.entry_tab)
		if a:bang == ""
		    call add(rhs_list, entry_tab)
		else
		    call add(rhs_list, 'i  '.entry[2].entry[3].space.entry_tab)
		endif
	    endif
	endfor
    endif
    let i = 0
    let i_list = []
    for rhs in rhs_list
	if rhs =~? a:rhs_pattern
	    call add(i_list, i)
	endif
	let i+=1
    endfor

    let found_maps = []
    for i in i_list
	call add(found_maps, list[i])
    endfor
    if len(found_maps) > 0
	echo join(found_maps, "\n")
    else
	echohl WarningMsg
	echo "No matches found"
	echohl None
    endif
endfunction
" }}}1

" vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1
autoload/atplib/motion.vim	[[[1
2229
" Author:	Marcin Szamotulski
" Description:	This file contains motion and highlight functions of ATP.
" Note:		This file is a part of Automatic Tex Plugin for Vim.
" Language:	tex
" Last Change:

" All table  of contents stuff: variables, functions and commands. 
" {{{1 __Table_of_Contents__
"--Make TOC -----------------------------
" This makes sense only for latex documents.
"
" Notes: Makeing toc from aux file:
" 	+ is fast
" 	+ one gets correct numbers
" 	- one doesn't get line numbers
" 		/ the title might be modified thus one can not make a pattern
" 		    which works in all situations, while this is important for 
" 		    :DeleteSection command /
"
" {{{2 atplib#motion#find_toc_lines
function! atplib#motion#find_toc_lines()
    let toc_lines_nr=[]
    let toc_lines=[]

    let pos_saved=getpos(".")
    let pos=[0,1,1,0]
    keepjumps call setpos(".",pos)

    " Pattern:
    let j=0
    for section in keys(g:atp_sections)
	if j == 0 
	    let pattern=g:atp_sections[section][0] . ''
	else
	    let pattern=pattern . '\|' . g:atp_sections[section][0] 
	endif
	let j+=1
    endfor

    " Searching Loop:
    let line=search(pattern, 'W')
    while line
	call add(toc_lines_nr, line)
	let line=search(pattern, 'W')
    endwhile
    keepjumps call setpos(".", pos_saved)
    for line in toc_lines_nr
	call add(toc_lines, getline(line))
    endfor
    return toc_lines
endfunction
" {{{2 atplib#motion#maketoc 
" this will store information: 
" { 'linenumber' : ['chapter/section/..', 'sectionnumber', 'section title', '0/1=not starred/starred'] }
" a:0 >= 1 avoid using atplib#search#SearchPackage('biblatex') (requires that b:atp_MainFile exists)
function! atplib#motion#maketoc(filename,...)
    let toc={}
    let search_package = ( a:0 >= 1 ? a:1 : 1 ) 

    " if the dictinary with labels is not defined, define it
    if !exists("t:atp_labels")
	let t:atp_labels = {}
    endif

    let texfile		= []
    " getbufline reads only loaded buffers, unloaded can be read from file.
    let bufname		= fnamemodify(a:filename,":t")
    try
	let texfile = ( bufexists(bufname)  ? getbufline("^" . bufname . "$","1","$") : readfile(a:filename) )
    catch /E484:/
	echohl Warning
	echo "File " . a:filename . " not readable."
	echohl None
    endtry
    let texfile_copy	= deepcopy(texfile)

    let true		= 1
    let bline		= 0 	" We are not removing the preambule any more.
    let i		= 1
    " set variables for chapter/section numbers
    for section in keys(g:atp_sections)
	let ind{section} = 0
    endfor
    " make a filter
    let j = 0
    let biblatex	= ( search_package ? atplib#search#SearchPackage("biblatex") : 0 )
    " When \usepackge{biblatex} do not search for \bibliography{} commands -- they are placed in the preambule.
    let key_list 	= ( biblatex ? filter(keys(g:atp_sections), "v:val != 'bibliography'") : keys(g:atp_sections) ) 
    for section in key_list
	let filter = ( j == 0 ? g:atp_sections[section][0] . '' : filter . '\|' . g:atp_sections[section][0] )
	let j+=1
    endfor

    let s:filtered	= filter(deepcopy(texfile), 'v:val =~ filter')
    let line_number = -1
    for line in s:filtered
	let line_number+=1
	for section in keys(g:atp_sections)
	    if line =~ g:atp_sections[section][0] 
		if line !~ '^\s*\\\@<!%'
		    " THIS DO NOT WORKS WITH \abstract{ --> empty set, but with
		    " \chapter{title} --> title, solution: the name of
		    " 'Abstract' will be plased, as we know what we have
		    " matched
		    let title	= line
" This is an attempt to join consecutive lines iff the title is spanned
" through more than one line.
" s:filtered doesn't is not the same as texfile!!!
" we should use texfile, but for this we need to know the true line numbers,
" they should be around though.
" 		    let open=count(split(title, '\zs'), '{')
" 		    let closed=count(split(title, '\zs'), '}')
" 		    let i=0
" 		    if open!=closed
" 			echomsg "XXXXXXX"
" 			echomsg title
" 		    endif
" 		    while open!=closed && line_number+i+2<=len(s:filtered)
" 			echomsg i." ".s:filtered[line_number+i]
" 			let i+=1 
" 			let open+=count(split(s:filtered[line_number+i], '\zs'), '{')
" 			let closed+=count(split(s:filtered[line_number+i], '\zs'), '}')
" 			let title.=" ".substitute(s:filtered[line_number+i], '^\s*', '', '')
" 		    endwhile

		    " test if it is a starred version.
		    let star=0
		    if g:atp_sections[section][1] != 'nopattern' && line =~ g:atp_sections[section][1] 
			let star=1 
		    else
			let star=0
		    endif

		    " Problem: If there are two sections with the same title, this
		    " does't work:
		    let idx	= index(texfile,line)
		    call remove(texfile, idx)
		    let i	= idx
		    let tline	= i+bline+1
		    let bline	+=1

		    " Find Title:
		    let start	= stridx(title,'{')+1
		    let title	= strpart(title,start)
		    " we are looking for the maching '}' 
		    let l:count	= 1
		    let i=-1
		    while i<=len(title)
			let i+=1
			if strpart(title,i,1) == '{'	
			    let l:count+=1
			elseif strpart(title,i,1) == '}'
			    let l:count-=1
			endif
			if l:count == 0
			    break
			endif
		    endwhile	
		    let title = strpart(title,0,i)
		    let title = substitute(title, '[{}]\|\\titlefont\|\\hfill\=\|\\hrule\|\\[vh]space\s*{[^}]\+}', '', 'g')

		    " Section Number:
		    " if it is not starred version add one to the section number
		    " or it is not an abstract 
		    if star == 0  
			if !(section == 'chapter' && title =~ '^\cabstract$')
			    let ind{section}+=1
			endif
		    endif

		    if section == 'part'
			let indchapter		= 0
			let indsection		= 0
			let indsubsection	= 0
			let indsubsubsection	= 0
		    elseif section ==  'chapter'
			let indsection		= 0
			let indsubsection	= 0
			let indsubsubsection	= 0
		    elseif section ==  'section' || section == 'frame'
			let indsubsection	= 0
			let indsubsubsection	= 0
		    elseif section ==  'subsection'
			let indsubsubsection	= 0
		    endif

		    " Find Short Title:
		    let shorttitle=line
		    let start=stridx(shorttitle,'[')+1
		    if start == 0
			let shorttitle=''
		    else
			let shorttitle=strpart(shorttitle,start)
			" we are looking for the maching ']' 
			let l:count=1
			let i=-1
			while i<=len(shorttitle)
			    let i+=1
			    if strpart(shorttitle,i,1) == '['	
				let l:count+=1
			    elseif strpart(shorttitle,i,1) == ']'
				let l:count-=1
			    endif
			    if l:count==0
				break
			    endif
			endwhile	
			let shorttitle = strpart(shorttitle,0,i)
		    endif

		    "ToDo: if section is bibliography (using bib) then find the first
		    " empty line:
		    if section == "bibliography" && line !~ '\\begin\s*{\s*thebibliography\s*}' && !biblatex
			let idx	= tline-1
			while texfile_copy[idx] !~ '^\s*$'
			    let idx-= 1
			endwhile
" 			" We add 1 as we want the first non blank line, and one more
" 			" 1 as we want to know the line number not the list index
" 			" number:
			let tline=idx+1
		    endif

		    " Add results to the dictionary:
		    if biblatex && section != "bibliography" || !biblatex
			call extend(toc, { tline : [ section, ind{section}, title, star, shorttitle] }) 
		    endif

		endif
	    endif
	endfor
    endfor
"     if exists("t:atp_toc")
" 	call extend(t:atp_toc, { a:filename : toc }, "force")
"     else
" 	let t:atp_toc = { a:filename : toc }
"     endif
"     return t:atp_toc
    return { a:filename : toc }
endfunction
"
" {{{2 atplib#motion#maketoc_py
function! atplib#motion#maketoc_py(filename,...)
    " filename is supposed to be b:atp_MainFile
if exists("s:py_toc")
    unlet s:py_toc
endif
python << END
import vim, fileinput, sys, re, os, os.path

# main file
file_name = vim.eval("a:filename")
# Change the directory to the main file
main_dir = os.path.dirname(file_name)
if main_dir != '':
    os.chdir(main_dir)

section_pattern         = re.compile('^[^%]*\\\\(subsection|section|chapter|part)(\*)?\s*(?:\[|{)')
shorttitle_pattern      = re.compile('^[^%]*\\\\(subsection|section|chapter|part)(\*)?\s*\[')
subfile_pattern         = re.compile('^[^%]*\\\\(input|include|subfile)\s*{([^}]*)}')

# the toc list:
toc = []
# toc = [ [file_name, line_nr, section_unit, title, short_title, star ], ... ]
# after the section number will be computed (depending on section/parts/ ..., 
# or it might be taken from the aux file)

# the list of files:
file_list = [[file_name, 'root', 0]]
# file_list = [ [ file, subfile, lnr ], ... ]

def map_none(val):
    if val == None:
	return ''
    else:
	return val

def add_extension(fname):
# add tex extension if the file has no extension,

    if os.path.splitext(fname)[1] != '.tex':
        return os.path.join(main_dir,fname+".tex")
    else:
        return os.path.join(main_dir,fname)

def find_in_brackets( string, bra = '{', ket = '}' ):
# find string in brackets {...},

    if bra in string:
        match = string.split(bra, 1)[1]
        open = 1
        for index in xrange(len(match)):
            if match[index] == bra:
                open += 1
            elif match[index] == ket:
                open -= 1
            if not open:
                return match[:index]


def scan_project(fname):
# scan file for section units starting after line start_line,

    try:
        file_o = open(add_extension(fname), 'r')
        file = file_o.readlines()
        length = len(file)
        for ind in xrange(length):
            line = file[ind]
            secu = re.search(section_pattern, line)
            subf = re.search(subfile_pattern, line)
            if secu:
		# Join lines (find titles if they are spread in more than one line):
                i = 1
                while i+ind < length and i < 6:
                    line += file[ind+i]
                    i+=1
                if re.search(shorttitle_pattern, line):
                    short_title = find_in_brackets( line, '[', ']')
                    short_title = re.sub('\s*\n\s*', ' ', short_title)
                else:
                    short_title = ''
                title = find_in_brackets( line, '{', '}')
                if title != None:
                    title = re.sub('\s*\n\s*', ' ', title)
                else:
                    title = ''
                # sec_nr is added afterwards.
                add = [ add_extension(fname), ind+1, secu.group(1), title, short_title, secu.group(2)]
                toc.append(map(map_none,add))
            if subf:
                file_list.append(map(map_none,[add_extension(fname), subf.group(2), ind+1]))
                scan_project(subf.group(2))
    except IOError:
        print("[ATP]: can not open "+add_extension(fname)+" cwd="+os.getcwd())
        pass


scan_project(file_name)

def check_sec(sec_name,toc):
# Check if there is a section sec_name in toc

    def filter_toc(val):
        if val[2] == sec_name:
            return True
        else:
            return False
    return len(filter(filter_toc,toc)) > 0

has_part = check_sec('part', toc)
has_chapter = check_sec('chapter', toc)
has_section = check_sec('section', toc)
if len(toc) > 0:
    p_nr = 0
    c_nr = 0
    s_nr = 0
    ss_nr = 0
    sss_nr = 0
    for i in range(0,len(toc)):
        if toc[i][2] == 'part' and toc[i][5] == '':
            p_nr += 1
            c_nr = 0
            s_nr = 0
            ss_nr = 0
            sss_nr = 0
        elif toc[i][2] == 'chapter' and toc[i][5] == '':
            c_nr += 1
            s_nr = 0
            ss_nr = 0
            sss_nr = 0
        elif toc[i][2] == 'section' and toc[i][5] == '':
            s_nr += 1
            ss_nr = 0
            sss_nr = 0
        elif toc[i][2] == 'subsection' and toc[i][5] == '':
            ss_nr += 1
            sss_nr = 0
        elif toc[i][2] == 'subsubsection' and toc[i][5] == '':
            sss_nr += 1
        if toc[i][5] == '*':
            sec_nr = "*"
        else:
            if has_part:
                if toc[i][2] == 'part':
                    sec_nr = str(p_nr)
                elif toc[i][2] == 'chapter':
                    sec_nr = str(p_nr)+"."+str(c_nr)
                elif toc[i][2] == 'section':
                    sec_nr = str(p_nr)+"."+str(c_nr)+"."+str(s_nr)
                elif toc[i][2] == 'subsection':
                    sec_nr = str(p_nr)+"."+str(c_nr)+"."+str(s_nr)+"."+str(ss_nr)
                elif toc[i][2] == 'subsubsection':
                    sec_nr = str(p_nr)+"."+str(c_nr)+"."+str(s_nr)+"."+str(ss_nr)+"."+str(sss_nr)
            elif has_chapter:
                if toc[i][2] == 'chapter':
                    sec_nr = str(c_nr)
                elif toc[i][2] == 'section':
                    sec_nr = str(c_nr)+"."+str(s_nr)
                elif toc[i][2] == 'subsection':
                    sec_nr = str(c_nr)+"."+str(s_nr)+"."+str(ss_nr)
                elif toc[i][2] == 'subsubsection':
                    sec_nr = str(c_nr)+"."+str(s_nr)+"."+str(ss_nr)+"."+str(sss_nr)
            elif has_section:
                if toc[i][2] == 'section':
                    sec_nr = str(s_nr)
                elif toc[i][2] == 'subsection':
                    sec_nr = str(s_nr)+"."+str(ss_nr)
                elif toc[i][2] == 'subsubsection':
                    sec_nr = str(s_nr)+"."+str(ss_nr)+"."+str(sss_nr)
        toc[i] = toc[i]+[sec_nr]


vim.command("let s:py_toc="+re.sub('\\\\\\\\', '\\\\', str(toc)))
END
return { a:filename : s:py_toc }
endfunction
" {{{2 atplib#motion#buflist
function! atplib#motion#buflist()
    " this names are used in TOC and passed to atplib#motion#maketoc, which
    " makes a dictionary whose keys are the values of name defined
    " just below:
    if !exists("t:atp_toc_buflist")
	let t:atp_toc_buflist = []
    endif
    if g:atp_python_toc
        let name = atplib#FullPath(b:atp_MainFile)
    else
        let name=resolve(fnamemodify(bufname("%"),":p")) " add an entry to the list t:atp_toc_buflist if it is not there.
    endif
    if bufname("") =~ ".tex" && index(t:atp_toc_buflist,name) == -1
        if index(t:atp_toc_buflist,name) == -1
            call add(t:atp_toc_buflist,name)
        endif
    endif
    return t:atp_toc_buflist
endfunction
" {{{2 tplib#motion#RemoveFromToC
function! atplib#motion#RemoveFromToC(file)
    if a:file == ""
	if exists("b:atp_MainFile")
	    let list = filter(copy(t:atp_toc_buflist), "v:val != fnamemodify(b:atp_MainFile, ':p')")
	else
	    let list = copy(t:atp_toc_buflist)
	endif
	if len(list) >= 2
	    let i=1
	    for f in list
		echo "(" . i . ") " . f
		let i+=1
	    endfor
	    let which=input("Which file to remove (press <Enter> for none)")
	    if which == ""
		return
	    endif
	    let which=t:atp_toc_buflist[which-1]
	elseif exists("b:atp_MainFile") && len(list) == 1
	    let which=get(list,0,"")
	else
	    return
	endif
    else
	let which = fnamemodify(a:file, ":p")
    endif

    if which != ""
	silent! call remove(t:atp_toc_buflist,index(t:atp_toc_buflist, which))
	silent! call remove(t:atp_toc,which)
    endif
    let winnr=winnr()
    if index(map(tabpagebuflist(), 'bufname(v:val)'), '__ToC__') != -1
	call atplib#motion#TOC("!", 0, 0)
    endif
    exe winnr."wincmd w"
endfunction
function! atplib#motion#RemoveFromToCComp(A, B, C)
    return join(t:atp_toc_buflist,"\n")
endfunction
" {{{2 atplib#motion#showtoc
function! atplib#motion#showtoc(toc)

    " this is a dictionary of line numbers where a new file begins.
    let cline=line(".")
"     " Open new window or jump to the existing one.
"     " Remember the place from which we are coming:
    let t:atp_bufname=atplib#FullPath(expand("%:t"))
"     let t:atp_winnr=winnr()	 these are already set by TOC()
    let bname="__ToC__"
    let tocwinnr=bufwinnr(bufnr("^".bname."$"))
    if tocwinnr != -1
	" Jump to the existing window.
	exe tocwinnr . " wincmd w"
	setl modifiable noreadonly
	silent exe "%delete _"
    else
	" Open new window if its width is defined (if it is not the code below
	" will put toc in the current buffer so it is better to return.
	if !exists("t:toc_window_width")
	    let t:toc_window_width = g:atp_toc_window_width
	endif
	let labels_winnr=bufwinnr(bufnr("__Labels__"))
	if labels_winnr != -1
	    exe labels_winnr."wincmd w"
	    let split_cmd = "above split"
	else
	    let split_cmd = "vsplit"
	endif
	let toc_winnr=bufwinnr(bufnr("__ToC__"))
	if toc_winnr == -1
	    let openbuffer="keepalt " . (labels_winnr == -1 ? t:toc_window_width : ''). split_cmd." +setl\\ buftype=nofile\\ modifiable\\ noreadonly\\ noswapfile\\ bufhidden=delete\\ nobuflisted\\ tabstop=1\\ filetype=toc_atp\\ nowrap\\ nonumber\\ norelativenumber\\ winfixwidth\\ nobuflisted\\ nospell\\ cursorline __ToC__"
	    keepalt silent exe openbuffer
	else
	    exe toc_winnr."wincmd w"
	    setl modifiable noreadonly
	endif
    endif
    let number=1
    " this is the line number in ToC.
    " number is a line number relative to the file listed in ToC.
    " the current line number is linenumber+number
    " there are two loops: one over linenumber and the second over number.
    let numberdict	= {}
    let s:numberdict	= numberdict
    unlockvar b:atp_Toc
    let b:atp_Toc	= {}
    " this variable will be used to set the cursor position in ToC.
    for openfile in keys(a:toc)
	call extend(numberdict, { openfile : number })
	let part_on=0
	let chap_on=0
	let chnr=0
	let secnr=0
	let ssecnr=0
	let sssecnr=0
	for line in keys(a:toc[openfile])
	    if a:toc[openfile][line][0] == 'chapter'
		let chap_on=1
		break
	    elseif a:toc[openfile][line][0] == 'part'
		let part_on=1
	    endif
	endfor
	let sorted	= sort(keys(a:toc[openfile]), "atplib#CompareNumbers")
	let len		= len(sorted)
	" write the file name in ToC (with a full path in paranthesis)
	call setline(number,fnamemodify(openfile,":t") . " (" . fnamemodify(openfile,":p:h") . ")")
	call extend(b:atp_Toc, { number : [ openfile, 1 ]}) 
	let number+=1
	for line in sorted
	    call extend(b:atp_Toc,  { number : [ openfile, line ] })
	    let lineidx=index(sorted,line)
	    let nlineidx=lineidx+1
	    if nlineidx< len(sorted)
		let nline=sorted[nlineidx]
	    else
		let nline=line("$")
	    endif
	    let lenght=len(line) 	
	    if lenght == 0
		let showline="     "
	    elseif lenght == 1
		let showline="    " . line
	    elseif lenght == 2
		let showline="   " . line
	    elseif lenght == 3
		let showline="  " . line
	    elseif lenght == 4
		let showline=" " . line
	    elseif lenght>=5
		let showline=line
	    endif
	    " Print ToC lines.
	    if a:toc[openfile][line][0] == 'abstract' || a:toc[openfile][line][2] =~ '^\cabstract$'
		call setline(number, showline . "\t" . "  " . "Abstract" )
	    elseif a:toc[openfile][line][0] =~ 'bibliography\|references'
		call setline (number, showline . "\t" . "  " . a:toc[openfile][line][2])
	    elseif a:toc[openfile][line][0] == 'part'
		let partnr=a:toc[openfile][line][1]
		let nr=partnr
		if a:toc[openfile][line][3]
		    "if it is stared version
		    let nr=substitute(nr,'.',' ','')
		endif
		if a:toc[openfile][line][4] != ''
" 		    call setline (number, showline . "\t" . nr . " " . a:toc[openfile][line][4])
		    call setline (number, showline . "\t" . " " . a:toc[openfile][line][4])
		else
" 		    call setline (number, showline . "\t" . nr . " " . a:toc[openfile][line][2])
		    call setline (number, showline . "\t" . " " . a:toc[openfile][line][2])
		endif
	    elseif a:toc[openfile][line][0] == 'chapter'
		let chnr=a:toc[openfile][line][1]
		let nr=chnr
		if a:toc[openfile][line][3]
		    "if it is stared version
		    let nr=substitute(nr,'.',' ','')
		endif
		if a:toc[openfile][line][4] != ''
		    call setline (number, showline . "\t" . nr . " " . a:toc[openfile][line][4])
		else
		    call setline (number, showline . "\t" . nr . " " . a:toc[openfile][line][2])
		endif
	    elseif a:toc[openfile][line][0] == 'section' || a:toc[openfile][line][0] == 'frame'
		let secnr=a:toc[openfile][line][1]
		if chap_on
		    let nr=chnr . "." . secnr  
		    if a:toc[openfile][line][3]
			"if it is stared version
			let nr=substitute(nr,'.',' ','g')
		    endif
		    if a:toc[openfile][line][4] != ''
			call setline (number, showline . "\t\t" . nr . " " . a:toc[openfile][line][4])
		    else
			call setline (number, showline . "\t\t" . nr . " " . a:toc[openfile][line][2])
		    endif
		else
		    let nr=secnr 
		    if a:toc[openfile][line][3]
			"if it is stared version
			let nr=substitute(nr,'.',' ','g')
		    endif
		    if a:toc[openfile][line][4] != ''
			call setline (number, showline . "\t" . nr . " " . a:toc[openfile][line][4])
		    else
			call setline (number, showline . "\t" . nr . " " . a:toc[openfile][line][2])
		    endif
		endif
	    elseif a:toc[openfile][line][0] == 'subsection'
		let ssecnr=a:toc[openfile][line][1]
		if chap_on
		    let nr=chnr . "." . secnr  . "." . ssecnr
		    if a:toc[openfile][line][3]
			"if it is stared version 
			let nr=substitute(nr,'.',' ','g')
		    endif
		    if a:toc[openfile][line][4] != ''
			call setline (number, showline . "\t\t\t" . nr . " " . a:toc[openfile][line][4])
		    else
			call setline (number, showline . "\t\t\t" . nr . " " . a:toc[openfile][line][2])
		    endif
		else
		    let nr=secnr  . "." . ssecnr
		    if a:toc[openfile][line][3]
			"if it is stared version 
			let nr=substitute(nr,'.',' ','g')
		    endif
		    if a:toc[openfile][line][4] != ''
			call setline (number, showline . "\t\t" . nr . " " . a:toc[openfile][line][4])
		    else
			call setline (number, showline . "\t\t" . nr . " " . a:toc[openfile][line][2])
		    endif
		endif
	    elseif a:toc[openfile][line][0] == 'subsubsection'
		let sssecnr=a:toc[openfile][line][1]
		if chap_on
		    let nr=chnr . "." . secnr . "." . sssecnr  
		    if a:toc[openfile][line][3]
			"if it is stared version
			let nr=substitute(nr,'.',' ','g')
		    endif
		    if a:toc[openfile][line][4] != ''
			call setline(number, a:toc[openfile][line][0] . "\t\t\t" . nr . " " . a:toc[openfile][line][4])
		    else
			call setline(number, a:toc[openfile][line][0] . "\t\t\t" . nr . " " . a:toc[openfile][line][2])
		    endif
		else
		    let nr=secnr  . "." . ssecnr . "." . sssecnr
		    if a:toc[openfile][line][3]
			"if it is stared version 
			let nr=substitute(nr,'.',' ','g')
		    endif
		    if a:toc[openfile][line][4] != ''
			call setline (number, showline . "\t\t" . nr . " " . a:toc[openfile][line][4])
		    else
			call setline (number, showline . "\t\t" . nr . " " . a:toc[openfile][line][2])
		    endif
		endif
	    else
		let nr=""
	    endif
	    let number+=1
	endfor
    endfor
    " set the cursor position on the correct line number.
    " first get the line number of the begging of the ToC of t:atp_bufname
    " (current buffer)
    " 	let t:numberdict=numberdict	"DEBUG
    " 	t:atp_bufname is the full path to the current buffer.
    let num = get(numberdict, t:atp_bufname, 'no_number')
    if num == 'no_number'
	setl nomodifiable
	return
    endif
    let sorted		= sort(keys(a:toc[t:atp_bufname]), "atplib#CompareNumbers")
    let t:sorted	= sorted
    for line in sorted
	if cline>=line
	    let num+=1
	endif
    keepjumps call setpos('.',[bufnr(""),num,1,0])
    endfor
   
    " Help Lines:
    if search('<Enter> jump and close', 'nW') == 0
	call append('$', [ '', 			
		\ '_       set',
		\ '<Space> jump', 
		\ '<Enter> jump and close', 	
		\ 's       jump and split', 
		\ 'y or c  yank label', 	
		\ 'p       paste label', 
		\ 'q       close', 		
		\ 'zc	     fold section[s]',
		\ ":'<,'>Fold",
		\ ':YankSection', 
		\ ':DeleteSection', 
		\ ':PasteSection[!]', 		
		\ ':SectionStack', 
		\ ':Undo' ])
    endif
    setl nomodifiable
    lockvar 3 b:atp_Toc
endfunction
" {{{2 atplib#motion#show_pytoc
function! atplib#motion#show_pytoc(toc)


    " this is a dictionary of line numbers where a new file begins.
    let cline=line(".")
"     " Open new window or jump to the existing one.
"     " Remember the place from which we are coming:
    let t:atp_bufname=atplib#FullPath(expand("%:t"))
    let bname="__ToC__"
    let tabpagebufdict = {}
    for bufnr in tabpagebuflist()
	if fnamemodify(bufname(bufnr), ":t") != ""
	    let tabpagebufdict[fnamemodify(bufname(bufnr), ":t")]=bufnr
	endif
    endfor
    if index(keys(tabpagebufdict), "__ToC__") != -1
	let tocwinnr = bufwinnr(tabpagebufdict["__ToC__"])
    else
	let tocwinnr = -1
    endif

    if tocwinnr != -1
	" Jump to the existing window.
	    exe tocwinnr . " wincmd w"
	    setl modifiable noreadonly
	    silent exe "%delete _"
    else
	" Open new window if its width is defined (if it is not the code below
	" will put toc in the current buffer so it is better to return.
	if !exists("t:toc_window_width")
	    let t:toc_window_width = g:atp_toc_window_width
	endif
	let labels_winnr=bufwinnr(bufnr("__Labels__"))
	if labels_winnr != -1
	    exe labels_winnr."wincmd w"
	    let split_cmd = "above split"
	else
	    let split_cmd = "vsplit"
	endif
	let toc_winnr=bufwinnr(bufnr("__ToC__"))
	if toc_winnr == -1
	    let openbuffer="keepalt " . (labels_winnr == -1 ? t:toc_window_width : ''). split_cmd." +setl\\ buftype=nofile\\ modifiable\\ noreadonly\\ noswapfile\\ bufhidden=delete\\ nobuflisted\\ tabstop=1\\ filetype=toc_atp\\ nowrap\\ nonumber\\ norelativenumber\\ winfixwidth\\ nospell\\ cursorline __ToC__"
	    keepalt silent exe openbuffer
	else
	    exe toc_winnr."wincmd w"
	    setl modifiable noreadonly
	endif
    endif
    let number=1
    " this is the line number in ToC.
    " number is a line number relative to the file listed in ToC.
    " the current line number is linenumber+number
    " there are two loops: one over linenumber and the second over number.
    let numberdict	= {}
    let s:numberdict	= numberdict
    unlockvar b:atp_Toc
    let b:atp_Toc	= {}
    " this variable will be used to set the cursor position in ToC.
    for openfile in keys(a:toc)
	call extend(numberdict, { openfile : number })
	" write the file name in ToC (with a full path in paranthesis)
	call setline(number,fnamemodify(openfile,":t") . " (" . fnamemodify(openfile,":p:h") . ")")
        " openfile is the project name
	call extend(b:atp_Toc, { number : [ openfile, 1, openfile ]}) 
	let number+=1
        let lineidx = -1
	for line_list in a:toc[openfile]
            let line = line_list[1]
	    call extend(b:atp_Toc,  { number : [ line_list[0], line, openfile ] })
            let lineidx+=1
	    let nlineidx=lineidx+1
	    if nlineidx < len(a:toc[openfile])
		let nline=a:toc[openfile][nlineidx][1]
	    else
		let nline=line("$")
	    endif
	    let lenght=len(line)
	    if lenght == 0
		let showline="     "
	    elseif lenght == 1
		let showline="    " . line
	    elseif lenght == 2
		let showline="   " . line
	    elseif lenght == 3
		let showline="  " . line
	    elseif lenght == 4
		let showline=" " . line
	    elseif lenght>=5
		let showline=line
	    endif
	    " Print ToC lines.
	    if line_list[2] == 'abstract' || line_list[3] =~ '^\cabstract$'
		call setline(number, showline . "\t" . "  " . "Abstract" )
	    elseif line_list[2] =~ 'bibliography\|references'
		call setline (number, showline . "\t" . "  " . a:toc[openfile][line][2])
	    else
		let secnr=get(line_list,6,"XXX") " there might not bee section number in the line_list
                let nr=secnr 
                if line_list[4] != ''
                    call setline (number, showline . "\t" . nr . " " . line_list[4])
                else
                    call setline (number, showline . "\t" . nr . " " . line_list[3])
                endif
	    endif
	    let number+=1
	endfor
    endfor
    " set the cursor position on the correct line number.
    " first get the line number of the begging of the ToC of t:atp_bufname
    " (current buffer)
    let MainFile    = atplib#FullPath(getbufvar(bufnr(t:atp_bufname), "atp_MainFile"))
    let num 	= get(s:numberdict, MainFile, 'no_number')
    if num == 'no_number'
	return
    endif
    let sorted	= t:atp_pytoc[MainFile]
    let num_list=[0]
    let f_test = ( t:atp_bufname == atplib#FullPath(getbufvar(bufnr(t:atp_bufname), "atp_MainFile")) )
    for ind in range(0,len(sorted)-1)
	let line_l = sorted[ind]
        if g:atp_python_toc
	    " t:atp_bufname buffer from which :TOC was invoked.
	    let f_test_p = f_test
	    let f_test   = ( !f_test && t:atp_bufname == line_l[0] ? 1 : f_test )
	    if f_test && !f_test_p
		call add(num_list, ind+1)
	    endif
	    if t:atp_bufname == line_l[0] && (str2nr(cline) >= str2nr(line_l[1]))
		call add(num_list, ind+1)
	    endif
        else
            let line = line_l
            if cline>=line
                let num+=1
            else
                break
            endif
        endif
    endfor
    if g:atp_python_toc
	let num = max(num_list)+1
	keepjumps call setpos('.', [0,0,0,0])
	keepjumps call search('^'.escape(fnamemodify(MainFile, ":t"), '.\/').'\s\+(.*)\s*$', 'cW')
	exe "normal! ".(num-1)."j"
    else
	keepjumps call setpos('.',[bufnr(""),num,1,0])
    endif
   
    " Help Lines:
    if search('<Enter> jump and close', 'nW') == 0
	call append('$', [ '', 			
		\ '_       set',
		\ '<Space> jump', 
		\ '<Enter> jump and close', 	
		\ 's       jump and split', 
		\ 'y or c  yank label', 	
		\ 'p       paste label', 
		\ 'q       close', 		
		\ ':YankSection', 
		\ ':DeleteSection', 
		\ ':PasteSection[!]', 		
		\ ':SectionStack', 
		\ ':Undo' ])
" 		\ 'zc	     fold section[s]',
" 		\ ":'<,'>Fold",
    endif
    setl nomodifiable
    lockvar 3 b:atp_Toc
endfunction
" {{{2 atplib#motion#ToCbufnr()
" This function returns toc buffer number if toc window is not open returns -1.
function! atplib#motion#ToCbufnr() 
    let tabpagebufdict = {}
    for bufnr in tabpagebuflist()
	if fnamemodify(bufname(bufnr), ":t") != ""
	    " For QuickFix bufname is an empty string:
	    let tabpagebufdict[fnamemodify(bufname(bufnr), ":t")]=bufnr
	endif
    endfor
    if index(keys(tabpagebufdict), "__ToC__") != -1
	let tocbufnr = tabpagebufdict["__ToC__"]
    else
	let tocbufnr = -1
    endif
    return tocbufnr
endfunction
" atplib#motion#UpdateToCLine {{{2
function! atplib#motion#UpdateToCLine(...)
    let time = reltime()
    if !g:atp_UpdateToCLine
	return
    endif
    let toc_bufnr	= atplib#motion#ToCbufnr()
    let check_line 	= (a:0>=1 ? a:1 : -1) 
    if toc_bufnr == -1 || check_line != -1 && 
		\ getline(line(".")+check_line) !~# '\\\%(part\|chapter\|\%(sub\)\{0,2}section\)\s*{'
	return
    endif
    let cline  	= line(".")
    let cbufnr 	= bufnr("")
    let cwinnr	= bufwinnr("")
    exe bufwinnr(toc_bufnr)."wincmd w"
    let MainFile    = atplib#FullPath(getbufvar(bufnr(t:atp_bufname), "atp_MainFile"))
    if g:atp_python_toc
        let num 	= get(s:numberdict, MainFile, 'no_number')
    else
        let num 	= get(s:numberdict, t:atp_bufname, 'no_number')
    endif
    if num == 'no_number'
	exe cwinnr."wincmd w"
	return
    endif
    if g:atp_python_toc
        let sorted	= t:atp_pytoc[MainFile]
    else
        let sorted	= sort(keys(t:atp_toc[t:atp_bufname]), "atplib#CompareNumbers")
    endif
    let num_list = [0]
    let g:sorted=deepcopy(sorted)
    let f_test = ( t:atp_bufname == atplib#FullPath(getbufvar(bufnr(t:atp_bufname), "atp_MainFile")) )
    for ind in range(0,len(sorted)-1)
	let line_l = sorted[ind]
        if g:atp_python_toc
	    " t:atp_bufname buffer from which :TOC was invoked.
	    let f_test_p = f_test
	    let f_test   = ( !f_test && t:atp_bufname == line_l[0] ? 1 : f_test )
	    if f_test && !f_test_p
		call add(num_list, ind+1)
	    endif
	    if t:atp_bufname == line_l[0] && (str2nr(cline) >= str2nr(line_l[1]))
		call add(num_list, ind+1)
	    endif
        else
            let line = line_l
            if cline>=line
                let num+=1
            else
                break
            endif
        endif
    endfor
    let savedview = winsaveview()
    if g:atp_python_toc
	let savedview = winsaveview()
	let num = max(num_list)+1
	keepjumps call setpos('.', [0,0,0,0])
	keepjumps call search('^'.escape(fnamemodify(MainFile, ":t"), '.\/').'\s\+(.*)\s*$', 'cW')
	exe "normal! ".(num-1)."j"
    else
	keepjumps call setpos('.',[bufnr(""),num,1,0])
    endif
    if line(".") == savedview['lnum']
	call winrestview(savedview)
    endif

    call atplib#tools#CursorLine()

    let eventignore=&eventignore
    set eventignore+=BufEnter
    exe cwinnr."wincmd w"
    let &eventignore=eventignore
    let g:time_UpdateTocLine = reltimestr(reltime(time))
endfunction
" This is User Front End Function 
" atplib#motion#TOC {{{2
function! atplib#motion#TOC(bang,...)
    let time = reltime()
    " skip generating t:atp_toc list if it exists and if a:0 != 0
    if &l:filetype != 'tex' && &l:filetype != 'toc_atp'   
	echoerr "Wrong 'filetype'. This command works only for latex documents."
	return
    endif
    if a:0 == 0 
	call atplib#motion#buflist()
    endif
    let search_package = ( a:0 >= 2 ? a:2 : 1 ) " avoid using atplib#search#SearchPackage() in atplib#motion#maketoc()
    " for each buffer in t:atp_toc_buflist (set by atplib#motion#buflist)
    if ( a:bang == "!" || !exists("t:atp_toc") || g:atp_python_toc )
	if !g:atp_python_toc
	    let t:atp_toc = {}
	else
	    let t:atp_pytoc = {}
	endif
	for buffer in t:atp_toc_buflist 
            if g:atp_python_toc
		update
                call extend(t:atp_pytoc, atplib#motion#maketoc_py(buffer,search_package))
            else
                call extend(t:atp_toc, atplib#motion#maketoc(buffer,search_package))
            endif
	endfor
    endif
    if g:atp_python_toc
        call atplib#motion#show_pytoc(t:atp_pytoc)
    else
        call atplib#motion#showtoc(t:atp_toc)
    endif
    let g:time_TOC = reltimestr(reltime(time))
endfunction
nnoremap <Plug>ATP_TOC			:call atplib#motion#TOC("")<CR>

" This finds the name of currently eddited section/chapter units. 
" {{{2 atplib#motion#NearestSection
" This function finds the section name of the current section unit with
" respect to the dictionary a:section={ 'line number' : 'section name', ... }
" it returns the [ section_name, section line, next section line ]
function! atplib#motion#NearestSection(section)
    let cline=line('.')

    let sorted=sort(keys(a:section), "atplib#CompareNumbers")
    let x=0
    while x<len(sorted) && sorted[x]<=cline
       let x+=1 
    endwhile
    if x>=1 && x < len(sorted)
	let section_name=a:section[sorted[x-1]]
	return [section_name, sorted[x-1], sorted[x]]
    elseif x>=1 && x >= len(sorted)
	let section_name=a:section[sorted[x-1]]
	return [section_name,sorted[x-1], line('$')]
    elseif x<1 && x < len(sorted)
	" if we are before the first section return the empty string
	return ['','0', sorted[x]]
    elseif x<1 && x >= len(sorted)
	return ['', '0', line('$')]
    endif
endfunction
" {{{2 atplib#motion#ctoc
function! atplib#motion#ctoc()
    if &l:filetype != 'tex' || expand("%:e") != 'tex'
" TO DO:
" 	if  exists(g:tex_flavor)
" 	    if g:tex_flavor != "latex"
" 		echomsg "CTOC: Wrong 'filetype'. This function works only for latex documents."
" 	    endif
" 	endif
	" Set the status line once more, to remove the CTOC() function.
	call ATPStatus(0,0)
	return []
    endif
    " resolve the full path:
    let t:atp_bufname = expand("%:p")
    
    " if t:atp_toc(t:atp_bufname) exists use it otherwise make it 
    if !exists("t:atp_toc") || !has_key(t:atp_toc, t:atp_bufname) 
	if !exists("t:atp_toc")
	    let t:atp_toc = {}
	endif
	call extend(t:atp_toc, atplib#motion#maketoc(t:atp_bufname))
    endif

    " l:count where the preambule ends
    let buffer=getbufline(bufname("%"),"1","$")
    let i=0
    let line=buffer[0]
    while line !~ '\\begin\s*{document}' && i < len(buffer)
	let line=buffer[i]
	if line !~ '\\begin\s*{document}' 
	    let i+=1
	endif
    endwhile
	
    " if we are before the '\\begin{document}' line: 
    if line(".") <= i
	let return=['Preambule']
	return return
    endif

    let chapter={}
    let section={}
    let subsection={}

    for key in keys(t:atp_toc[t:atp_bufname])
	if t:atp_toc[t:atp_bufname][key][0] == 'chapter'
	    " return the short title if it is provided
	    if t:atp_toc[t:atp_bufname][key][4] != ''
		call extend(chapter, {key : t:atp_toc[t:atp_bufname][key][4]},'force')
	    else
		call extend(chapter, {key : t:atp_toc[t:atp_bufname][key][2]},'force')
	    endif
	elseif t:atp_toc[t:atp_bufname][key][0] == 'section'
	    " return the short title if it is provided
	    if t:atp_toc[t:atp_bufname][key][4] != ''
		call extend(section, {key : t:atp_toc[t:atp_bufname][key][4]},'force')
	    else
		call extend(section, {key : t:atp_toc[t:atp_bufname][key][2]},'force')
	    endif
	elseif t:atp_toc[t:atp_bufname][key][0] == 'subsection'
	    " return the short title if it is provided
	    if t:atp_toc[t:atp_bufname][key][4] != ''
		call extend(subsection, {key : t:atp_toc[t:atp_bufname][key][4]},'force')
	    else
		call extend(subsection, {key : t:atp_toc[t:atp_bufname][key][2]},'force')
	    endif
	endif
    endfor

    " Remove $ from chapter/section/subsection names to save the space.
    let chapter_name=substitute(atplib#motion#NearestSection(chapter)[0],'\$\|\\(\|\\)','','g')
    let chapter_line=atplib#motion#NearestSection(chapter)[1]
    let chapter_nline=atplib#motion#NearestSection(chapter)[2]

    let section_name=substitute(atplib#motion#NearestSection(section)[0],'\$\|\\(\|\\)','','g')
    let section_line=atplib#motion#NearestSection(section)[1]
    let section_nline=atplib#motion#NearestSection(section)[2]
"     let b:section=atplib#motion#NearestSection(section)		" DEBUG

    let subsection_name=substitute(atplib#motion#NearestSection(subsection)[0],'\$\|\\(\|\\)','','g')
    let subsection_line=atplib#motion#NearestSection(subsection)[1]
    let subsection_nline=atplib#motion#NearestSection(subsection)[2]
"     let b:ssection=atplib#motion#NearestSection(subsection)		" DEBUG

    let names	= [ chapter_name ]
    if (section_line+0 >= chapter_line+0 && section_line+0 <= chapter_nline+0) || chapter_name == '' 
	call add(names, section_name) 
    elseif subsection_line+0 >= section_line+0 && subsection_line+0 <= section_nline+0
	call add(names, subsection_name)
    endif
    return names
endfunction
" Labels Front End Finction. The search engine/show function are in autoload/atplib.vim script
" library.
" }}}1

" {{{1 atplib#motion#Labels
" a:bang = "!" do not regenerate labels if not necessary
function! atplib#motion#Labels(bang)
    let t:atp_bufname	= expand("%:p")
    let error		= ( exists("b:atp_TexReturnCode") ? b:atp_TexReturnCode : 0 )
    let atp_MainFile	= atplib#FullPath(b:atp_MainFile)

    " Generate the dictionary with labels
    if a:bang == "" || ( a:bang == "!" && !exists("t:atp_labels") ) ||
		\ ( a:bang == "!" && exists("t:atp_labels") && get(t:atp_labels, atp_MainFile, []) == [] )
	let [ t:atp_labels, b:ListOfFiles ] =  atplib#tools#generatelabels(atp_MainFile, 1)
    endif

    " Show the labels in seprate window
    call atplib#tools#showlabels([ t:atp_labels, map(extend([b:atp_MainFile], copy(b:ListOfFiles)), 'atplib#FullPath(v:val)')])

    if error
	echohl WarningMsg
	redraw
	echomsg "[ATP:] the compelation contains errors, aux file might be not appriopriate for labels window."
	echohl None
    endif
endfunction
nnoremap <Plug>ATP_Labels		:call atplib#motion#Labels("")<CR>

" atplib#motion#GotoLabel {{{1
" a:bang = "!" do not regenerate labels if not necessary
" This is developed for one tex project in a vim.
function! atplib#motion#GotoLabel(bang,...)

    let alabel = ( a:0 == 0 ? "" : a:1 )

    let atp_MainFile	= atplib#FullPath(b:atp_MainFile)
    " Generate the dictionary with labels
    if a:bang == "" || ( a:bang == "!" && ( !exists("b:ListOfFiles") || !exists("t:atp_labels") ) )
	let [ t:atp_labels, b:ListOfFiles ] =  atplib#tools#generatelabels(atp_MainFile, 1)
    endif

    let matches = []
    for file in keys(t:atp_labels)
	if index(b:ListOfFiles, fnamemodify(file, ":t")) != -1 || index(b:ListOfFiles, file) != -1 || file == atplib#FullPath(b:atp_MainFile)
	    for label in t:atp_labels[file]
		if label[1] =~ alabel || label[2] =~ '^'.alabel
		    call add(matches, extend([file], label))
		endif
	    endfor
	endif
    endfor

    if len(matches) == 0
	redraw
	echohl WarningMsg
	echomsg "[ATP:] no matching label"
	echohl None
	return 1
    elseif len(matches) == 1
	let file=matches[0][0]
	let line=matches[0][1]
    else
" 	if len(keys(filter(copy(b:TypeDict), 'v:val == "input"'))) == 0
	    let mlabels=map(copy(matches), "[(index(matches, v:val)+1).'.', v:val[2],v:val[3]]")
" 	else
" 	Show File from which label comes
" 	The reason to not use this is as follows: 
" 		it only matters for project files, which probably have many
" 		labels, so it's better to make the list as concise as possible
" 	    let mlabels=map(copy(matches), "[(index(matches, v:val)+1).'.', v:val[2], v:val[3], fnamemodify(v:val[0], ':t')]")
" 	    let file=1 
" 	endif
	echohl Title
	echo "Which label to choose?"
	echohl None
" 	let mlabels= ( file ? extend([[' nr', 'LABEL', 'LABEL NR', 'FILE']], mlabels) : extend([[' nr', 'LABEL', 'LABEL NR']], mlabels) )
	for row in atplib#FormatListinColumns(atplib#Table(mlabels, [1,2]),2)
	    echo join(row)
	endfor
	let nr = input("Which label to choose? type number and press <Enter> ")-1
	if nr < 0 || nr >= len(matches)
	    return
	endif
	let file=matches[nr][0]
	let line=matches[nr][1]
    endif

    " Check if the buffer is loaded.
    if bufloaded(file)
	execute "b " . file
	call cursor(line,1)
    else
	execute "edit " . file
	call cursor(line,1)
    endif
endfunction
" atplib#motion#GotoLabelCompletion {{{1
function! atplib#motion#GotoLabelCompletion(ArgLead, CmdLine, CursorPos)

    let atp_MainFile	= atplib#FullPath(b:atp_MainFile)
    " Generate the dictionary with labels (only if it doesn't exist)
    if !exists("t:atp_labels") || t:atp_labels == {} || !exists("b:ListOfFiles") || a:CmdLine !~# '^GotoLabel!'
	let [ t:atp_labels, b:ListOfFiles ] =  atplib#tools#generatelabels(atp_MainFile, 1)
" It would be nice to delete the ! from the cmdline after this step. There are
" only getcmdline(), getcmdpos() and setcmdpos() functions available.
	let cmd_line=substitute(getcmdline(), "GotoLabel!", "GotoLabel", "")
    endif

    let labels=[]
    for file in keys(t:atp_labels)
	if index(b:ListOfFiles, fnamemodify(file, ":t")) != -1 || index(b:ListOfFiles, file) != -1 || file == atplib#FullPath(b:atp_MainFile)
	    call extend(labels, map(deepcopy(t:atp_labels)[file], 'v:val[1]'))
	    call extend(labels, map(deepcopy(t:atp_labels)[file], 'v:val[2]'))
	endif
    endfor
    call filter(labels, "v:val !~ '^\s*$' && v:val =~ a:ArgLead ")

    return map(labels, "v:val.'\\>'")
endfunction
" atplib#motion#LatexTags {{{1
function! atplib#motion#LatexTags(bang,...)
    " a:1 == 1 :  silent
    let silent = ( ( a:0 ? a:1 : 0 ) ? ' --silent ' : ' ' )
    let hyperref_cmd = ( atplib#search#SearchPackage("hyperref") ? " --hyperref " : "" )
    if has("clientserver")
	let servername 	= " --servername ".v:servername." "
	let progname	= " --progname ".v:progname." " 
    else
	let servername 	= ""
	let progname	= ""
    endif
    let bibtags = ( a:bang == "" ? " --bibtags " : "" )
    " Write file:
    call atplib#write('nobackup')

    let latextags=split(globpath(&rtp, "ftplugin/ATP_files/latextags.py"), "\n")[0]
    let files=join(
		\ map([b:atp_MainFile]+filter(copy(keys(b:TypeDict)), "b:TypeDict[v:val] == 'input'"), 'atplib#FullPath(v:val)')
		\ , ";")
    
    if len(filter(copy(keys(b:TypeDict)), "b:TypeDict[v:val] == 'bib'")) >= 1
	let bibfiles=join(filter(copy(keys(b:TypeDict)), "b:TypeDict[v:val] == 'bib'"), ";")
	let bib= " --bibfiles ".shellescape(bibfiles) 
    else
	let bib= " --bibtags_env "
    endif
    let dir 	= expand("%:p:h")
    if atplib#search#SearchPackage("biblatex")
	let cite = " --cite biblatex "
    elseif atplib#search#SearchPackage("natbib")
	let cite = " --cite natbib "
    else
	let cite = " "
    endif

    let cmd=g:atp_Python." ".shellescape(latextags).
		\ " --files ".shellescape(files).
		\ " --auxfile ".shellescape(fnamemodify(atplib#FullPath(b:atp_MainFile), ":r").".aux").
		\ " --dir ".shellescape(dir).
		\ bib . cite . silent .
		\ hyperref_cmd . servername . progname . bibtags . " &"
    if g:atp_debugLatexTags
	let g:cmd=cmd
    endif
    call system(cmd)
endfunction
"{{{1 atplib#motion#GotoDestination
function! atplib#motion#GotoNamedDestination(destination)
    if b:atp_Viewer !~ '^\s*xpdf\>' 
	echomsg "[ATP:] this only works with Xpdf viewer."
	return 0
    endif
    let cmd='xpdf -remote '.b:atp_XpdfServer.' -exec gotoDest\("'.a:destination.'"\)'
    call system(cmd)
endfunction
function! atplib#motion#FindDestinations()
    let files = [ b:atp_MainFile ]
    if !exists("b:TypeDict")
	call TreeOfFiles(b:atp_MainFile)
    endif
    for file in keys(b:TypeDict)
	if b:TypeDict[file] == 'input'
	    call add(files, file)
	endif
    endfor
    let saved_loclist = getloclist(0)
    exe 'lvimgrep /\\hypertarget\>/gj ' . join(map(files, 'fnameescape(v:val)'), ' ') 
    let dests = []
    let loclist	= copy(getloclist(0))
    call setloclist(0, saved_loclist)
    for loc in loclist
	let destname = matchstr(loc['text'], '\\hypertarget\s*{\s*\zs[^}]*\ze}')
	call add(dests, destname)
    endfor
    return dests
endfunction
function! atplib#motion#CompleteDestinations(ArgLead, CmdLine, CursorPos)
    let dests=atplib#motion#FindDestinations()
    return join(dests, "\n")
endfunction

" Motion functions through environments and sections. 
"  atplib#motion#GotoEnvironment {{{1
" which name is given as the argument. Do not wrap
" around the end of the file.
function! atplib#motion#GotoEnvironment(flag,count,...)

    " Options :
    let env_name 	= ( a:0 >= 1 && a:1 != ""  ? a:1 : '[^}]*' )
    if env_name == 'part'
	if a:flag =~ 'b'
	    exe a:count.'PPart'
	    return
	else
	    exe a:count.'NPart'
	    return
	endif
    elseif env_name  == 'chapter' 
	if a:flag =~ 'b'
	    exe a:count.'PChap'
	    return
	else
	    exe a:count.'NChap'
	    return
	endif
    elseif env_name == 'section' 
	if a:flag =~ 'b'
	    exe a:count.'PSec'
	    return
	else
	    exe a:count.'NSec'
	    return
	endif
    elseif env_name == 'subsection' 
	if a:flag =~ 'b'
	    exe a:count.'PSSec'
	    return
	else
	    exe a:count.'NSSec'
	    return
	endif
    elseif env_name == 'subsubsection' 
	if a:flag =~ 'b'
	    exe a:count.'PSSSec'
	    return
	else
	    exe a:count.'NSSSec'
	    return
	endif
    endif

    let flag = a:flag
    
    " Set the search tool :
    " Set the pattern : 
    if env_name == 'math'
	let pattern = '\m\%(\(\\\@<!\\\)\@<!%.*\)\@<!\%(\%(\\begin\s*{\s*\%(\(displayed\)\?math\|\%(fl\)\?align\|eqnarray\|equation\|gather\|multline\|subequations\|xalignat\|xxalignat\)\s*\*\=\s*}\)\|\\\@<!\\\[\|\\\@<!\\(\|\\\@<!\$\$\=\)'
    elseif env_name == 'displayedmath'
	let pattern = '\m\%(\(\\\@<!\\\)\@<!%.*\)\@<!\%(\%(\\begin\s*{\s*\%(displayedmath\|\%(fl\)\?align\*\=\|eqnarray\*\=\|equation\*\=\|gather\*\=\|multline\*\=\|xalignat\*\=\|xxalignat\*\=\)\s*}\)\|\\\@<!\\\[\|\\\@!\$\$\)'
    elseif env_name == 'inlinemath'
	let pattern = '\m\%(\(\\\@<!\\\)\@<!%.*\)\@<!\%(\\begin\s*{\s*math\s*}\|\\\@<!\\(\|\$\@<!\\\@<!\$\$\@!\)'
    else
	let pattern = '\m\%(\(\\\@<!\\\)\@<!%.*\)\@<!\\begin\s*{\s*' . env_name 
    endif


    " Search (twise if needed)
    for i in range(1, a:count)
	if i > 1
	    " the 's' flag should be used only in the first search. 
	    let flag=substitute(flag, 's', '', 'g') 
	endif
	if g:atp_mapNn
	    let search_cmd 	= "S /"
	    let search_cmd_e= "/ " . flag
	else
	    let search_cmd	= "silent! call search('"
	    let search_cmd_e= "','" . flag . "')"
	endif
	execute  search_cmd . pattern . search_cmd_e
	if a:flag !~# 'b'
	    if getline(".")[col(".")-1] == "$" 
		if ( get(split(getline("."), '\zs'), col(".")-1, '') == "$" && get(split(getline("."), '\zs'), col("."), '') == "$" )
		    "check $$
		    let rerun = !atplib#complete#CheckSyntaxGroups(['texMathZoneY'], line("."), col(".")+1 )
		elseif get(split(getline("."), '\zs'), col(".")-1, '') == "$" 
		    "check $
		    let rerun = !atplib#complete#CheckSyntaxGroups(['texMathZoneX', 'texMathZoneY'], line("."), col(".") )
		endif
		if rerun
		    silent! execute search_cmd . pattern . search_cmd_e
		endif
	    endif
	else " a:flag =~# 'b'
	    if getline(".")[col(".")-1] == "$" 
		if ( get(split(getline("."), '\zs'), col(".")-1, '') == "$" && get(split(getline("."), '\zs'), col(".")-2, '') == "$" )
		    "check $$
		    let rerun = atplib#complete#CheckSyntaxGroups(['texMathZoneY'], line("."), col(".")-3 )
		elseif get(split(getline("."), '\zs'), col(".")-1, '') == "$" 
		    "check $
		    let rerun = atplib#complete#CheckSyntaxGroups(['texMathZoneX', 'texMathZoneY'], line("."), col(".")-2 )
		endif
		if rerun
		    silent! execute search_cmd . pattern . search_cmd_e
		endif
	    endif
	endif
    endfor

    call atplib#motion#UpdateToCLine()
    silent! call histadd("search", pattern)
    silent! let @/  = pattern
    return ""
endfunction
" atplib#motion#GotoFrame {{{1
function! atplib#motion#GotoFrame(f, count)
    let lz=&lazyredraw
    set lazyredraw
    if a:f == "backward"
	call atplib#motion#GotoEnvironment('bsW', a:count, 'frame')
    else
	call atplib#motion#GotoEnvironment('sW', a:count, 'frame')
    endif
    normal! zt
    let &lz=lz
endfunction
nnoremap <Plug>NextFrame	:<C-U>call atplib#motion#GotoFrame('forward', v:count1)<CR>
nnoremap <Plug>PreviousFrame	:<C-U>call atplib#motion#GotoFrame('backward', v:count1)<CR>
" atplib#motion#JumptoEnvironment {{{1 
" function! atplib#motion#GotoEnvironmentB(flag,count,...)
"     let env_name 	= (a:0 >= 1 && a:1 != ""  ? a:1 : '[^}]*')
"     for i in range(1,a:count)
" 	let flag 	= (i!=1?substitute(a:flag, 's', '', 'g'):a:flag)
" 	call atplib#motion#GotoEnvironment(flag,1,env_name)
"     endfor
" endfunction
" Jump over current \begin and go to next one.
" i.e. if on line =~ \begin => % and then search, else search
function! atplib#motion#JumptoEnvironment(backward)
    call setpos("''", getpos("."))
    let lazyredraw=&l:lazyredraw
    set lazyredraw
    if !a:backward
	let col	= searchpos('\w*\>\zs', 'n')[1]-1
	if strpart(getline(line(".")), 0, col) =~ '\\begin\>$' &&
		    \ strpart(getline(line(".")), col) !~ '^\s*{\s*document\s*}'
	    exe "normal g%"
	endif
	call search('^\%([^%]\|\\%\)*\zs\\begin\>', 'W')
    else
	let found =  search('^\%([^%]\|\\%\)*\\end\>', 'bcW')
	if getline(line(".")) !~ '^\%([^%]\|\\%\)*\\end\s*{\s*document\s*}' && found
	    exe "normal %"
	elseif !found
	    call search('^\%([^%]\|\\%\)*\zs\\begin\>', 'bW')
	endif
    endif
    let &l:lazyredraw=lazyredraw
endfunction 
" atplib#motion#GotoSection {{{1 
" The extra argument is a pattern to match for the
" section title. The first, obsolete argument stands for:
" part,chapter,section,subsection,etc.
" This commands wrap around the end of the file.
" with a:3 = 'vim' it uses vim search() function
" with a:3 = 'atp' 
" the default is: 
" 	if g:atp_mapNn then use 'atp'
" 	else use 'vim'.
function! atplib#motion#GotoSection(bang, count, flag, secname, ...)
    let search_tool		= ( a:0 >= 1 ? a:1	: ( g:atp_mapNn ? 'atp' : 'vim' ) )
    let mode			= ( a:0 >= 2 ? a:2	: 'n' )
    let title_pattern 		= ( a:0 >= 3 ? a:3	: ''  )
    let pattern = ( empty(a:bang) ? '^\([^%]\|\\\@<!\\%\)*' . a:secname . title_pattern : a:secname . title_pattern )

    if getline(line(".")) =~ pattern
	" If we are on the line that matches go to begining of this line, so
	" that search will find previous match unless the flag contains 'c'.
	call cursor(line("."), 1)
    endif

    " This is not working ?:/
    " just because it goes back to the mark '< and searches again:
"     if mode == 'v' | call cursor(getpos("'<")[1], getpos("'<")[2]) | endif
"     if mode == 'v' && visualmode() ==# 'V'
" 	normal! V
"     elseif mode == 'v' 
" 	normal! v
"     endif
"     let bpat = ( mode == 'v' 	? "\\n\\s*" : "" ) 
    let bpat 	= "" 
    let flag	= a:flag
    for i in range(1,a:count)
	if i > 1
	    " the 's' flag should be used only in the first search. 
	    let flag=substitute(flag, 's', '', 'g') 
	endif
	if search_tool == 'vim'
	    call searchpos(bpat . pattern, flag)
	else
	    execute "S /". bpat . pattern . "/ " . flag 
	endif
    endfor

    call atplib#motion#UpdateToCLine()
    call histadd("search", pattern)
    let @/ = pattern
endfunction
function! atplib#motion#Env_compl(A,P,L) 
    let envlist=sort(['algorithm', 'algorithmic', 'abstract', 'definition', 'equation', 'proposition', 
		\ 'theorem', 'lemma', 'array', 'tikzpicture', 
		\ 'tabular', 'table', 'align', 'alignat', 'proof', 
		\ 'corollary', 'enumerate', 'examples\=', 'itemize', 'remark', 
		\ 'notation', 'center', 'quotation', 'quote', 'tabbing', 
		\ 'picture', 'math', 'displaymath', 'minipage', 'list', 'flushright', 'flushleft', 
		\ 'frame', 'figure', 'eqnarray', 'thebibliography', 'titlepage', 
		\ 'verbatim', 'verse', 'inlinemath', 'displayedmath', 'subequations',
		\ 'part', 'section', 'subsection', 'subsubsection' ])
    let returnlist=[]
    for env in envlist
	if env =~ '^' . a:A 
	    call add(returnlist,env)
	endif
    endfor
    return returnlist
endfunction

function! atplib#motion#ggGotoSection(count,section)
    let mark  = getpos("''")
    if a:section == "part"
	let secname = '\\part\>'
	call cursor(1,1)
    elseif a:section == "chapter"
	let secname = '\\\%(part\|chapter\)\>'
	if !search('\\part\>', 'bc')
	    call cursor(1,1)
	endif
    elseif a:section == "section"
	let secname = '\\\%(part\|chapter\|section\)\>'
	if !search('\\chapter\>\|\\part\>', 'bc')
	    call cursor(1,1)
	endif
    elseif a:section == "subsection"
	let secname = '\\\%(part\|chapter\|section\|subsection\)\>'
	if !search('\\section\>\|\\chapter\>\|\\part\>', 'bc')
	    call cursor(1,1)
	endif
    elseif a:section == "subsubsection"
	let secname = '\\\%(part\|chapter\|section\|subsection\|subsubsection\)\>'
	if !search('\subsection\>\|\\section\>\|\\chapter\>\|\\part\>', 'bc')
	    call cursor(1,1)
	endif
    endif
    call atplib#motion#UpdateToCLine()
    call atplib#motion#GotoSection("", a:count, 'Ws', secname)
    call setpos("''",mark)
endfunction

" atplib#motion#Input {{{1 
function! atplib#motion#Input(flag)
    let pat 	= ( &l:filetype == "plaintex" ? '\\input\s*{' : '\%(\\input\s*{\=\>'.(atplib#search#SearchPackage('subfiles') ?  '\|\\subfile\s*{' : '' ).'\|\\include\s*{\)' )
    let @/	= '^\([^%]\|\\\@<!\\%\)*' . pat
    if g:atp_mapNn
	exe ':S /^\([^%]\|\\\@<!\\%\)*' .  pat . '/ ' . a:flag
    else
	call search('^\([^%]\|\\\@<!\\%\)*' . pat, a:flag)
    endif
    call atplib#motion#UpdateToCLine()
    "     This pattern is quite simple and it might be not neccesary to add it to
    "     search history.
    "     call histadd("search", pat)
endfunction
" atplib#motion#GotoFile {{{1
" This function also sets filetype vim option.
" It is useing '\f' pattern thus it depends on the 'isfname' vim option.
try
    " NOTE: if the filetype is wrong the path will not be recognized
    " 		it is better to make it syntax independet!
    "
    " It let choose if there are multiple files only when this is fast
    " (\input{,\input ) methods. However, then the file name should be unique! 

    " It correctly sets b:atp_MainFile, and TreeOfFiles, ... variables in the new
    " buffer.
function! atplib#motion#GotoFile(bang,args,...)

    let edit_args = matchstr(a:args, '\zs\%(++\=\%(\%(\\\@<!\s\)\@<!.\)*\s*\)\=')
    let find_args = matchstr(a:args, '+/\(\(\\\@<!\s\)\@<!.\)*')
    let edit_args = substitute(edit_args, '+/\(\(\\\@<!\s\)\@<!.\)*', '', 'g')
    let file	= matchstr(matchstr(a:args, '\%(\\\@<!\s[^+]\)\=\%(\%(\\\@<!\s\)\@<!.\)*\s*'), '\s*\zs.*')
    let cwd	= getcwd()
    exe "lcd " . fnameescape(b:atp_ProjectDir)
    let atp_MainFile	= atplib#FullPath(b:atp_MainFile)

    " The default value is to check line if not stending on a comment.
    let check_line	= ( a:0 >= 1 ? a:1 : strpart(getline("."), 0, col(".")) !~ '\(\\\@<!\\\)\@<!%' )

    if !has("path_extra")
	echoerr "Needs +path_extra vim feature."
	exe "lcd " . cwd
	return
    endif	

    let filetype 	= &l:filetype

    if a:bang == "!" || !exists("b:TreeOfFiles") || !exists("b:ListOfFiles") || !exists("b:TypeDict") || !exists("b:LevelDict") 
	let [tree_d, file_l, type_d, level_d ] 	= TreeOfFiles(atp_MainFile)
    else
	let [tree_d, file_l, type_d, level_d ] 	= deepcopy([ b:TreeOfFiles, b:ListOfFiles, b:TypeDict, b:LevelDict ])
    endif

    " This is passed to the newly opened buffer.
    let projectVarDict = SaveProjectVariables()

    let file_l_orig = deepcopy(file_l)

    " Note: line is set to "" if check_line == 0 => method = "all" is used. 
    let line		= ( check_line ? getline(".") : "" )
    if check_line
	let beg_line	= strpart(line, 0,col(".")-1)
	" Find the begining column of the file name:
	let bcol	= searchpos('\%({\|,\)', 'bn',  line("."))[1]
	if bcol == 0
	    let bcol 	= searchpos('{', 'n', line("."))[1]
	endif

	" Find the end column of the file name
	let col		= searchpos(',\|}', 'cn', line("."))[1]
	" Current column
	let cur_col		= col(".")
    endif

    " This part will be omitted if check_line is 0 (see note above).
    " \usepackege{...,<package_name>,...}
    if line =~ '\\usepackage' && g:atp_developer
	let method = "usepackage"
	let ext 	= '.sty'

	let fname   	= atplib#append_ext(strpart(getline("."), bcol, col-bcol-1), ext)
	let file 	= atplib#search#KpsewhichFindFile('tex', fname, '', 1)
	let file_l	= [ file ]

	let message = "Pacakge: "
	let options = ""

    " \input{...}, \include{...}
    elseif line =~ '\\\(input\|include\|subfile\)\s*{' 
	let method = "input{"
	let ext 	= '.tex'

	" \input{} doesn't allow for {...,...} many file path. 
	let fname 	= atplib#append_ext(strpart(getline("."), bcol, col-bcol-1), '.tex')

	" The 'file . ext' might be already a full path.
	if fnamemodify(fname, ":p") != fname
	    let file_l 	= atplib#search#KpsewhichFindFile('tex', fname, g:atp_texinputs, -1, ':p', '^\(\/home\|\.\)', '\%(^\/usr\|kpsewhich\|texlive\|miktex\)')
	    let file	= get(file_l, 0, 'file_missing')
	else
	    let file_l	= [ fname ] 
	    let file	= fname
	endif


	let message = "File: "
	let options = ""

    " \input 	/without {/
    elseif line =~ '\\input\s*{\@!'
	let method = "input"
	let fname	= atplib#append_ext(matchstr(getline(line(".")), '\\input\s*\zs\f*\ze'), '.tex')
	let file_l	= atplib#search#KpsewhichFindFile('tex', fname, g:atp_texinputs, -1, ':p', '^\(\/home\|\.\)', '\%(^\/usr\|kpsewhich\|texlive\)')
	let file	= get(file_l, 0, "file_missing")
	let options = ' +setl\ ft=' . &l:filetype  
    " \documentclass{...}
    elseif line =~ '\\documentclass' && g:atp_developer
	let method = "documentclass"
	let saved_pos	= getpos(".")
	call cursor(line("."), 1)
	call search('\\documentclass\zs', 'cb', line("."))
	let bcol	= searchpos('{', 'c', line("."))[1]
	execute "normal %"
	let ecol	= col(".")
	call cursor(saved_pos[0], saved_pos[1])
	let classname 	= strpart(getline("."), bcol, ecol-bcol-1)
	let fname	= atplib#append_ext(classname, '.cls')
	let file	= atplib#search#KpsewhichFindFile('tex', fname,  g:atp_texinputs, 1, ':p')
	let file_l	= [ file ]
	let options	= ""
    elseif line =~ '\\RequirePackage' && g:atp_developer
	let method = "requirepackage"
	let ext 	= '.sty'
	let fname	= atplib#append_ext(strpart(getline("."), bcol, col-bcol-1), ext)
	let file	= atplib#search#KpsewhichFindFile('tex', fname, g:atp_texinputs, 1, ':p')
	let file_l	= [ file ]
	let options = ' +setl\ ft=' . &l:filetype  
    elseif line =~ '\\bibliography\>'
	let method 	= "bibliography"
	setl iskeyword +=\
	let fname	= expand("<cword>")
	setl iskeyword -=\
	if fname == "\\bibliography"
	    let fname 	= matchstr(getline(line(".")), '\\bibliography{\zs[^},]*\ze\%(,\|}\)')
	endif
	let fname 	= atplib#append_ext(fname, '.bib')
	let file_l	= atplib#search#KpsewhichFindFile('bib', fname, g:atp_bibinputs, -1, ':p', '^\(\/home\|\.\)', '\%(^\/usr\|kpsewhich\|texlive\)')
	let file	= get(file_l, 0, "file_missing")
	let options = ' +setl\ ft=' . &l:filetype  
    else 
	" If not over any above give a list of input files to open, like
	" EditInputFile  
	let method	= "all"

	call extend(file_l, [ atp_MainFile ], 0)
	call extend(level_d, { atp_MainFile : 0 })
    endif

"     let g:file_l = copy(file_l)
"     let g:method = method
"     let g:line 	= line

    if len(file_l) > 1 && file =~ '^\s*$'
	if method == "all"
	    let msg = "Which file to edit?"
	else
	    let msg = "Found many files. Which file to use?"
	endif
	let mods	= method == 'all' ? ":t" : ":p"
	" It is better to start numbering from 0,
	" then 	0 - is the main file 
	"	1 - is the first chapter, and so on.
	let i		= 0
	let input_l	= []
	for f in file_l
	    if exists("level_d")
		let space = ""
		if g:atp_RelativePath
		    exe "lcd " . fnameescape(b:atp_ProjectDir)
		    let level = get(level_d,fnamemodify(f, ':.'), get(level_d, f, 1))
		    exe "lcd " . fnameescape(cwd)
		else
		    exe "lcd " . fnameescape(b:atp_ProjectDir)
		    let level = get(level_d,f, get(level_d,fnamemodify(f, ':.'), 1))
		    exe "lcd " . fnameescape(cwd)
		endif
		for j in range(level)
		    let space .= "   "
		endfor
	    else
		space	= ""
	    endif
	    call add(input_l, "(" . i . ") " . space . fnamemodify(f, mods))
	    let i+=1
	endfor
	" Ask the user which file to edit:
	redraw
	if len([ msg ] + input_l) < &l:lines
	    for f in  [ msg ] + input_l
		" echo highlighted message
		if matchstr(f, '(\d\+)\s*\zs.*$') == expand("%:t")
		    echohl CursorLine
		elseif f == msg
		    echohl Title
		endif
		echo f
		if matchstr(f, '(\d\+)\s*\zs.*$') == expand("%:t") || f == msg
		    echohl None
		endif
	    endfor
	    let choice	= input("Type number and <Enter> (empty cancels): ")
	    if choice != "" 
		let choice	+= 1
	    endif
	elseif 
	    for line in [ msg ] + input_l
		if line == msg
		    echohl Title	
		endif
		echo line
		echohl None
	    endfor
	    echohl MoreMsg
	    let choice = input("Type number and <Enter> (empty cancels): ")
	    echohl None
	    if choice != "" 
		let choice	+= 1
	    endif
	endif
	" Remember: 0 == "" returns 1! 
	" char2nr("") = 0
	" nr2char(0) = ""
	if choice == ""
	    exe "lcd " . fnameescape(cwd)
	    return
	endif
	if choice < 1 || choice > len(file_l)
	    if choice < 1 || choice > len(file_l)
		echo "\n"
		echoerr "Choice out of range."
	    endif
	    exe "lcd " . fnameescape(cwd)
	    return
	endif
	let file 	= atplib#FullPath(file_l[choice-1])
	let fname 	= file
    elseif file !~ '^\s*$'
	let file 	= atplib#FullPath(file)
	let fname	= file
    endif

"     DEBUG
"     let g:fname  = fname
"     let g:file   = file 
"     let g:file_l = file_l
"     let g:choice = choice 

    if !exists("file")
	exe "lcd " . fnameescape(cwd)
	return
    endif

    if file != "file_missing" && filereadable(file) && ( !exists("choice") || exists("choice") && choice != 0 )

	" Inherit tex flavour.
	" So that bib, cls, sty files will have their file type (bib/plaintex).
	let filetype	= &l:filetype
	let old_file	= expand("%:p")
	execute "edit ".edit_args." ".escape(find_args, '\')." ".fnameescape(file)
	call RestoreProjectVariables(projectVarDict)
	if &l:filetype =~ 'tex$' && file =~ '\.tex$' && &l:filetype != filetype  
	    let &l:filetype	= filetype
	endif

	" Set the main file variable and pass the TreeOfFiles variables to the new
	" buffer.
	if exists("b:atp_ErrorFormat")
	    unlockvar b:atp_ErrorFormat
	endif
	return file
    else
	echohl ErrorMsg
	redraw
	if file != "file_missing" && exists("fname")
	    echo "File \'".fname."\' not found."
	else
	    echo "Missing file."
	endif
	echohl None

	exe "lcd " . fnameescape(cwd)
	return file
    endif
endfunction
catch /E127:/
endtry
function! atplib#motion#GotoFileComplete(ArgLead, CmdLine, CursorPos)
    let bang = ( a:CmdLine =~ '^\w*!' ? '!' : '')
    if bang == "!" || !exists("b:TreeOfFiles") || !exists("b:ListOfFiles") || !exists("b:TypeDict") || !exists("b:LevelDict") 
	let [tree_d, file_l, type_d, level_d ] 	= TreeOfFiles(atp_MainFile)
    else
	let [tree_d, file_l, type_d, level_d ] 	= deepcopy([ b:TreeOfFiles, b:ListOfFiles, b:TypeDict, b:LevelDict ])
    endif
    if index(file_l, b:atp_MainFile) == -1 || index(file_l, fnamemodify(b:atp_MailFile, ":p")) == -1 
	call add(file_l, b:atp_MainFile) 
    endif
    return  filter(file_l, "v:val =~ a:ArgLead")
endfunction
" atplib#motion#SkipComment {{{1
" a:flag=fb (f-forward, b-backward)
" f works like ]*
" b workd like [*
" Note: the 's' search flag is passed by the associated commands.
" This can be extended: 
" 	(1) skip empty lines between comments
function! atplib#motion#SkipComment(flag, mode, count, ...)
    let flag 	= ( a:flag =~ 'b' ? 'b' : '' ) 
    let nr	= ( a:flag =~ 'b' ? -1 : 1 )

    for c in range(1, a:count)
	let test = search('^\zs\s*%', flag)
	if !test
	    return
	endif
	call cursor(line("."), ( nr == -1 ? 1 : len(getline(line(".")))))

	let line	= getline(line("."))
	" find previous line
	let pline_nr=min([line("$"), max([1,line(".")+nr])])
	let pline	= getline(pline_nr) 

	while pline =~ '^\s*%' && line(".") != line("$") && line(".") != 1
	    call cursor(line(".")+nr, ( nr == -1 ? 1 : len(getline(line(".")+nr))))
	    let pline_nr=min([line("$"), max([1,line(".")+nr])])
	    let pline	= getline(pline_nr) 
	endwhile
	if a:mode == 'n' && ( !g:atp_VimCompatible || g:atp_VimCompatible =~? '\<no\>' )
	    if a:flag =~# 'b'
		call cursor(line(".")-1,1)
	    else
		call cursor(line(".")+1,1)
	    endif
	endif
	if a:mode == 'v'
	    let end_pos = [ line("."), col(".") ]
	    " Go where visual mode started
	    exe "normal `" . ( nr == 1 ? '<' : '>' ) 
	    exe "normal " . visualmode()
	    call cursor(end_pos)
	endif
    endfor
endfunction

" Syntax motion
" {{{1 atplib#motion#TexSyntaxMotion
function! atplib#motion#TexSyntaxMotion(forward, how, ...)

    " If the function is used in imap.
    let in_imap	= ( a:0 >= 1 ? a:1 : 0 )

    let whichwrap	= split(&l:whichwrap, ',')
    if !count(whichwrap, 'l') 
	setl ww+=l
    endif
    if !count(whichwrap, 'h')
	setl ww+=h
    endif

    " before we use <Esc> 
    let line=line(".")
    if in_imap && len(getline(".")) > col(".")
	let col = col(".")+1
    else
	let col = col(".")
    endif
"     execute "normal l"
    let step 		= ( a:forward > 0 ? "l" : "h" )
    let synstack	= map(synstack(line, col), 'synIDattr( v:val, "name")')
    let synstackh	= map(synstack(line, max([1, col-1])), 'synIDattr( v:val, "name")')

    let DelimiterCount	= count(synstack, 'Delimiter') 
    let ScriptCount	= count(synstack, 'texSuperscript') + count(synstack, 'texSubscript')
    let ScriptsCount	= count(synstack, 'texSuperscripts') + count(synstack, 'texSubscripts')
    let StatementCount	= count(synstack, 'texStatement')
    let StatementCounth	= count(synstackh, 'texStatement') && col(".") > 1
    let SectionCount	= count(synstack, 'texSection')

    let TypeStyleCount	= count(synstack, 'texTypeStyle')
    let TypeStyleCounth	= count(synstackh, 'texTypeStyle') && col(".") > 1
    let MathTextCount	= count(synstack, 'texMathText')
    let MathTextCounth	= count(synstackh, 'texMathText') && col(".") > 1
    let RefZoneCount	= count(synstack, 'texRefZone')
    let RefZoneCounth	= count(synstackh, 'texRefZone') && col(".") > 1 
    let RefOptionCount	= count(synstack, 'texRefOption')
    let RefOptionCounth	= count(synstackh, 'texRefOption') && !count(synstackh, 'Delimiter') && col(".") > 1
    let CiteCount	= count(synstack, 'texCite')
    let CiteCounth	= count(synstackh, 'texCite') && !count(synstackh, 'Delimiter') && col(".") > 1
    let MatcherCount 	= count(synstack, 'texMatcher')
    let MatcherCounth 	= count(synstackh, 'texMatcher') && !count(synstackh, 'Delimiter') && col(".") > 1
    let MathMatcherCount 	= count(synstack, 'texMathMatcher')
    let MathMatcherCounth 	= count(synstackh, 'texMathMatcher') && !count(synstackh, 'Delimiter') && col(".") > 1
    let SectionNameCount 	= count(synstack, 'texSectionName')
    let SectionNameCounth 	= count(synstackh, 'texSectionName') && !count(synstackh, 'Delimiter') && col(".") > 1
    let SectionMarkerCount 	= count(synstack, 'texSectionMarker')

    let SectionModifierCount 	= count(synstack, 'texSectionModifier')
    let SectionModifierCounth 	= count(synstackh, 'texSectionModifier') && !count(synstackh, 'Delimiter') && col(".") > 1
"     let MathZonesCount		= len(filter(copy(synstack), 'v:val =~ ''^texMathZone[A-Z]'''))

"     let g:col	= col(".")
"     let g:line	= line(".")

    if DelimiterCount 
	let syntax	= [ 'Delimiter' ]
    elseif StatementCount && StatementCounth && step == "h"
	let syntax	= [ 'texStatement' ]
    elseif StatementCount && step != "h"
	let syntax	= [ 'texStatement' ]
    elseif SectionCount 
	let syntax	= [ 'texSection' ]
    elseif ScriptCount
	if a:how == 1
	    let syntax	= [ 'texSuperscript', 'texSubscript']
	else
	    let syntax	= [ 'texSuperscripts', 'texSubscripts']
	endif
    elseif TypeStyleCount && TypeStyleCounth && step == "h"
	let syntax	= [ 'texTypeStyle' ]
    elseif TypeStyleCount && step != "h"
	let syntax	= [ 'texTypeStyle' ]
    elseif RefZoneCount && RefZoneCounth && step == "h"
	let syntax	= [ 'texRefZone' ]
    elseif RefZoneCount && step != "h"
	let syntax	= [ 'texRefZone' ]
    elseif RefOptionCount && RefOptionCounth && step == "h"
	let syntax	= [ 'texRefOption' ]
    elseif RefOptionCount && step != "h"
	let syntax	= [ 'texRefOption' ]
    elseif CiteCount && CiteCounth && step == "h"
	let syntax	= [ 'texCite' ]
    elseif CiteCount && step != "h"
	let syntax	= [ 'texCite' ]
    elseif MatcherCount && MatcherCounth && step == "h"
	let syntax	= [ 'texMatcher' ]
    elseif MatcherCount && step != "h"
	let syntax	= [ 'texMatcher' ]
    elseif MathMatcherCount && MathMatcherCounth && step == "h"
	let syntax	= [ 'texMathMatcher' ]
    elseif MathMatcherCount && step != "h"
	let syntax	= [ 'texMathMatcher' ]
    elseif SectionNameCount && SectionNameCounth && step == "h"
	let syntax	= [ 'texSectionName' ]
    elseif SectionNameCount && step != "h"
	let syntax	= [ 'texSectionName' ]
    elseif SectionMarkerCount
	let syntax	= [ 'texSectionMarker' ]
    elseif SectionModifierCount && SectionModifierCounth && step == "h"
	let syntax	= [ 'texSectionModifier' ]
    elseif SectionModifierCount && step != "h"
	let syntax	= [ 'texSectionModifier' ]
    elseif MathTextCount && MathTextCounth && step == "h"
	let syntax	= [ 'texMathText' ]
    elseif MathTextCount && step != "h"
	let syntax	= [ 'texMathText' ]
"     elseif MathZonesCount
"     This might be slow
"     but we might change 'normal l' to 'normal w'
" 	let syntax	= [ 'texMathZoneA', 'texMathZoneB', 'texMathZoneC', 'texMathZoneD', 'texMathZoneE', 'texMathZoneF', 'texMathZoneG', 'texMathZoneH', 'texMathZoneI', 'texMathZoneJ', 'texMathZoneK', 'texMathZoneL', 'texMathZoneT', 'texMathZoneV', 'texMathZoneW', 'texMathZoneX', 'texMathZoneY' ]
    else
	" Go after first Delimiter
	let i=0
	let DelimiterCount	= count(synstack, 'Delimiter') 
	while !DelimiterCount
	    exe "normal " . step
	    let synstack	= map(synstack(line("."), col(".")), 'synIDattr( v:val, "name")')
	    let DelimiterCount	= count(synstack, 'Delimiter') 
	    if i == 1
		let DelimiterCount = 0
	    endif
	    let i+=1
	endwhile
	if in_imap
	    normal a
	endif
	return "Delimiter motion"
    endif

    let true	= 0
    for syn in syntax
	let true += count(synstack, syn)
    endfor
    let initial_count	= true

    while true >= initial_count
	let true	= 0
	execute "normal " . step
	let synstack	= map(synstack(line("."), col(".")), 'synIDattr( v:val, "name")')
	for syn in syntax
	    let true += count(synstack, syn)
	endfor
    endwhile
    while getline(".")[col(".")] =~ '^{\|}\|(\|)\|\[\|\]$'
	exe "normal l"
    endwhile
    if getline(".")[col(".")-2] == "{"
	exe "normal h"
    endif
    let &l:whichwrap	= join(whichwrap, ',')
    if in_imap
	normal a
"     else
" 	normal l
    endif
    if step == "l" && syntax == [ 'Delimiter' ]
	normal h
    endif
endfunction

" ctrl-j motion
" atplib#motion#JMotion {{{1
" New <Ctrl-j> motion
function! atplib#motion#JMotion(flag)
" 	Note: pattern to match only commands which do not have any arguments:
" 	'\(\\\w\+\>\s*{\)\@!\\\w\+\>'
    let line = getline(".")
    if a:flag !~# 'b'
	let pline = strpart(line, col(".")-1)
	if pline =~ '[{]*}{'
	    call search('{.', 'e')
	    return
	endif
    else
	let pline = strpart(line, 0, col("."))
	if pline =~ '}{'
	    call search('}{', 'b')
	    normal! h
	    return
	endif
    endif
    if a:flag !~# 'b'
	let pattern = '\%(\]\zs\|{\zs\|}\zs\|(\zs\|)\zs\|\[\zs\|\]\zs\|\$\zs\|^\zs\s*$\|\(\\\w\+\>\s*{\)\@!\\\w\+\>\zs\)'
    else
	let pattern = '\%(\]\|{\|}\|(\|)\|\[\|\]\|\$\|^\s*$\|\(\\\w\+\>\s*{\)\@!\\\w\+\>\)'
    endif
    if getline(line(".")) =~ '&'
	let pattern = '\%(&\s*\zs\|^\s*\zs\)\|' . pattern
    endif

    "     let g:col = col(".") " sometimes this doesn't work - in normal mode go to
    "     end of line and press 'a' - then col(".") is not working!
"     let g:let = getline(line("."))[col(".")-1]
"     let g:con = getline(line("."))[col(".")-1] =~ '\%(\$\|{\|}\|(\|)\|\[\|\]\)' && col(".") < len(getline(line(".")))
    if getline(line("."))[col(".")-1] =~ '\%(\$\|{\|}\|(\|)\|\[\|\]\)' && a:flag !~# 'b'
	if col(".") == len(getline(line(".")))
	    execute "normal a "
	else
	    call cursor(line("."), col(".")+1)
	endif
	return
    else
	call search(pattern, a:flag)
	" In the imaps we use 'a' for the backward move and 'i' for forward move! 
	let condition = getline(line("."))[col(".")-1] =~ '\%(\$\|{\|}\|(\|)\|\[\|\]\)'
	if a:flag !~# 'b' && col(".") == len(getline(line("."))) && condition
" 	    Add a space at the end of line and move there
		execute "normal a "
	endif
    endif
endfunction
" }}}1
" atplib#motion#ParagraphNormalMotion {{{1
function! atplib#motion#ParagraphNormalMotion(backward,count)
    if a:backward != "b"
	for i in range(1,a:count)
	    call search('\(^\(\n\|\s\)*\n\s*\zs\S\|\zs\\par\>\|\%'.line("$").'l$\)', 'W')
	endfor
    else
	for i in range(1,a:count)
	    call search('\(^\(\n\|\s\)*\n\s*\zs\S\|\zs\\par\>\|^\%1l\)', 'Wb')
	endfor
    endif
endfunction
nmap <buffer> <Plug>ParagraphNormalMotionForward 	:<C-U>call atplib#motion#ParagraphNormalMotion('', v:count1)<CR>
nmap <buffer> <Plug>ParagraphNormalMotionBackward	:<C-U>call atplib#motion#ParagraphNormalMotion('b', v:count1)<CR>
" atplib#motion#StartVisualMode {{{1
function! atplib#motion#StartVisualMode(mode)
    let g:atp_visualstartpos = getpos(".")
    if a:mode ==# 'v'
	normal! v
    elseif a:mode ==# 'V'
	normal! V
    elseif a:mode ==# 'cv'
	exe "normal! \<c-v>"
    endif
endfunction
" atplib#motion#ParagraphVisualMotion {{{1
function! atplib#motion#ParagraphVisualMotion(backward,count)
    let cond = !atplib#CompareCoordinates(g:atp_visualstartpos[1:2],getpos("'>")[1:2])
"     let g:pos = string(g:atp_visualstartpos)." ".string(getpos("'<"))." ".string(getpos("'>"))." ".cond
    let bpos = g:atp_visualstartpos
    if a:backward != "b"
	if cond
	    call cursor(getpos("'<")[1:2])
	else
	    call cursor(getpos("'>")[1:2])
	endif
	for i in range(1,a:count)
	    let epos = searchpos('\(^\(\n\|\s\)*\n\ze\|\(\_s*\)\=\\par\>\|\%'.line("$").'l$\)', 'Wn')
	endfor
    else 
	if cond
	    call cursor(getpos("'<")[1:2])
	else
	    call cursor(getpos("'>")[1:2])
	endif
	for i in range(1,a:count)
	    let epos = searchpos('\(^\(\n\|\s\)*\n\ze\|\(\_s*\)\=\\par\>\|^\%1l\ze\)', 'Wnb')
	endfor
    endif
    call cursor(bpos[1:2])
    exe "normal ".visualmode()
    call cursor(epos)
endfunction
vmap <buffer> <silent> <Plug>ParagraphVisualMotionForward 	:<C-U>call atplib#motion#ParagraphVisualMotion('',v:count1)<CR>
vmap <buffer> <silent> <Plug>ParagraphVisualMotionBackward 	:<C-U>call atplib#motion#ParagraphVisualMotion('b',v:count1)<CR>
" vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1
autoload/atplib/search.vim	[[[1
2400
" Author:	Marcin Szamotulski
" Description:  This file provides searching tools of ATP.
" Note:		This file is a part of Automatic Tex Plugin for Vim.
" Language:	tex
" Last Change:Tue Sep 06, 2011 at 03:18  +0100

" Make a dictionary of definitions found in all input files.
" {{{ atplib#search#make_defi_dict_vim
" Comparing with ]D, ]d, ]i, ]I vim maps this function deals with multiline
" definitions.
"
" The output dictionary is of the form: 
" 	{ input_file : [ [begin_line, end_line], ... ] }
" a:1 	= buffer name to search in for input files
" a:3	= 1 	skip searching for the end_line
"
" ToDo: it is possible to check for the end using searchpairpos, but it
" operates on a list not on a buffer.
function! atplib#search#make_defi_dict_vim(bang,...)

    let atp_MainFile	= atplib#FullPath(b:atp_MainFile)
    let bufname	= a:0 >= 1 ? a:1 : atp_MainFile

    " pattern to match the definitions this function is also used to fine
    " \newtheorem, and \newenvironment commands  
    let pattern	= a:0 >= 2 ? a:2 : '\\def\|\\newcommand'

    let preambule_only	= ( a:bang == "!" ? 0 : 1 )

    " this is still to slow!
    let only_begining	= ( a:0 >= 3 ? a:3 : 0 )

    let defi_dict={}

    let inputfiles=atplib#search#FindInputFiles(bufname)
    let input_files=[]

    " TeX: How this work in TeX files.
    for inputfile in keys(inputfiles)
	if inputfiles[inputfile][0] != "bib" && ( !preambule_only || inputfiles[inputfile][0] == "preambule" )
	    call add(input_files, inputfiles[inputfile][2])
	endif
    endfor

    let input_files=filter(input_files, 'v:val != ""')
    if !count(input_files, atp_MainFile)
	call extend(input_files,[ atp_MainFile ])
    endif

    if len(input_files) > 0
    for inputfile in input_files
	let defi_dict[inputfile]=[]
	" do not search for definitions in bib files 
	"TODO: it skips lines somehow. 
	let ifile=readfile(inputfile)
	
	" search for definitions
	let lnr=1
	while (lnr <= len(ifile) && (!preambule_only || ifile[lnr-1] !~ '\\begin\s*{document}'))

	    let match=0

	    let line=ifile[lnr-1]
	    if substitute(line,'\\\@<!%.*','','') =~ pattern

		let b_line=lnr

		let lnr+=1	
		if !only_begining
		    let open=atplib#count(line,'{')    
		    let close=atplib#count(line,'}')
		    while open != close
			"go to next line and count if the definition ends at
			"this line
			let line	= ifile[lnr-1]
			let open	+=atplib#count(line,'{')    
			let close	+=atplib#count(line,'}')
			let lnr		+=1	
		    endwhile
		    let e_line	= lnr-1
		    call add(defi_dict[inputfile], [ b_line, e_line ])
		else
		    call add(defi_dict[inputfile], [ b_line, b_line ])
		endif
	    else
		let lnr+=1
	    endif
	endwhile
    endfor
    endif

    return defi_dict
endfunction "}}}
" {{{ atplib#search#make_defi_dict_py
" command! -nargs=* -bang MakeDefiDict  :call atplib#search#make_defi_dict_py(<q-bang>,<f-args>)
function! atplib#search#make_defi_dict_py(bang,...)

    let atp_MainFile	= atplib#FullPath(b:atp_MainFile)
    let bufname	= a:0 >= 1 ? a:1 : atp_MainFile
    " Not tested
    let pattern	= a:0 >= 2 ? a:2 : '\\def\|\\newcommand'
    " Not implemeted
    let preambule_only= a:bang == "!" ? 0 : 1
    let only_begining	= a:0 >= 3 ? a:3 : 0

    if a:bang == "!" || !exists("b:TreeOfFiles")
	 " Update the cached values:
	 let [ b:TreeOfFiles, b:ListOfFiles, b:TypeDict, b:LevelDict ] = TreeOfFiles(atp_MainFile)
    endif
    let [ Tree, List, Type_Dict, Level_Dict ] = deepcopy([ b:TreeOfFiles, b:ListOfFiles, b:TypeDict, b:LevelDict ])
 
python << ENDPYTHON
import re, subprocess, os, glob

def preambule_end(file):
# find linenr where preambule ends,

# file is list of lines
    nr=1
    for line in file:
        if re.search('\\\\begin\s*{\s*document\s*}', line):
            return nr
        nr+=1
    return 0

pattern=vim.eval("pattern")
type_dict=vim.eval("b:TypeDict")
main_file=vim.eval("atp_MainFile")
if int(vim.eval("preambule_only")) != 0:
    preambule_only=True
    files=[main_file]
    for f in type_dict.keys():
        if type_dict[f] == "preambule":
            files.append(f)
    main_file_ob=open(main_file, 'r')
    main_file_l=main_file_ob.read().split("\n")
    main_file_ob.close()
    preambule_end=preambule_end(main_file_l)
else:
    preambule_only=False
    files=[main_file]
    files.extend(vim.eval("b:ListOfFiles"))
if vim.eval("only_begining") != "0":
    only_begining=True
else:
    only_begining=False
def isnonempty(string):
    if str(string) == "":
        return False
    else:
        return True

if pattern == "":
    pat=".*"
else:
    pat=pattern

# Does the no comment work?
pattern=re.compile('^(?:[^%]|\\\\%)*(?:\\\\def|\\\\(?:re)?newcommand\s*{|\\\\providecommand\s*{|\\\\(?:re)?newenvironment\s*{|\\\\(?:re)?newtheorem\s*{|\\\\definecolor\s*{)')

defi_dict={}
for file in files:
    defi_dict[file]=[]
    lnr=1
    file_ob=open(file, 'r')
    file_l=file_ob.read().split("\n")
    file_ob.close()
    while lnr <= len(file_l) and ( preambule_only and ( file == main_file and lnr <= preambule_end or file != main_file ) or not preambule_only):
        line=file_l[lnr-1]
        if re.search(pattern, line):
            # add: no search in comments.
            b_lnr       = lnr
            if not only_begining:
                _open       = len(re.findall("({)", line))
                _close      = len(re.findall("(})", line))
                while _open != _close:
                    lnr+=1
                    line     = file_l[lnr-1]
                    _open   += len(re.findall("({)", line))
                    _close  += len(re.findall("(})", line))
                e_lnr        = lnr
                defi_dict[file].append([ b_lnr, e_lnr ])
            else:
                defi_dict[file].append([ b_lnr, b_lnr ])
            lnr         += 1
        else:
            lnr+=1
vim.command("let s:defi_dict_py="+str(defi_dict))
vim.command("let g:defi_dict_py="+str(defi_dict))
ENDPYTHON
return s:defi_dict_py
endfunction
"}}}

"{{{ atplib#search#LocalCommands_vim 
" a:1 = pattern
" a:2 = "!" => renegenerate the input files.
function! atplib#search#LocalCommands_vim(...)
"     let time = reltime()
    let pattern = a:0 >= 1 && a:1 != '' ? a:1 : '\\def\>\|\\newcommand\>\|\\newenvironment\|\\newtheorem\|\\definecolor\|'
		\ . '\\Declare\%(RobustCommand\|FixedFont\|TextFontCommand\|MathVersion\|SymbolFontAlphabet'
			    \ . '\|MathSymbol\|MathDelimiter\|MathAccent\|MathRadical\|MathOperator\)'
		\ . '\|\\SetMathAlphabet\>'
    let bang	= a:0 >= 2 ? a:2 : '' 

    let atp_MainFile	= atplib#FullPath(b:atp_MainFile)

    " Makeing lists of commands and environments found in input files
    if bang == "!" || !exists("b:TreeOfFiles")
	 " Update the cached values:
	 let [ b:TreeOfFiles, b:ListOfFiles, b:TypeDict, b:LevelDict ] = TreeOfFiles(atp_MainFile)
     endif
     let [ Tree, List, Type_Dict, Level_Dict ] = deepcopy([ b:TreeOfFiles, b:ListOfFiles, b:TypeDict, b:LevelDict ])

     let saved_loclist	= getloclist(0)
     " I should scan the preambule separately!
     " This will make the function twice as fast!
     silent! execute "lvimgrep /".pattern."/j " . fnameescape(atp_MainFile)
     for file in List
	 if get(Type_Dict, file, 'no_file') == 'preambule'
	     silent! execute "lvimgrepadd /".pattern."/j " . fnameescape(file)
	 endif
     endfor
     let loclist	= getloclist(0)
     call setloclist(0, saved_loclist)

     let atp_LocalCommands	= []
     let atp_LocalEnvironments	= []
     let atp_LocalColors	= []

     for line in loclist
	" the order of pattern is important
	if line['text'] =~ '^[^%]*\\definecolor'
	    " color name
	    let name=matchstr(line['text'],
			\ '\\definecolor\s*{\s*\zs[^}]*\ze\s*}')
	    let type="Colors"
	elseif line['text'] =~ '^[^%]*\%(\\def\>\|\\newcommand\)'
	    " definition name 
	    let name= '\' . matchstr(line['text'], '\\def\\\zs[^{]*\ze{\|\\newcommand{\?\\\zs[^\[{]*\ze}')
	    let name=substitute(name, '\(#\d\+\)\+\s*$', '', '')
            let name.=(line['text'] =~ '\\def\\\w\+#[1-9]\|\\newcommand{[^}]*}\[[1-9]\]' ? '{' : '')
	    if name =~ '#\d\+'
		echo line['text']
		echo name
	    endif
	    let type="Commands"
	    " definition
" 	    let def=matchstr(line['text'],
" 			\ '^\%(\\def\\[^{]*{\zs.*\ze}\|\\newcommand\\[^{]*{\zs.*\ze}\)') 
	elseif line['text'] =~ '^[^%]*\%(\\Declare\%(RobustCommand\|FixedFont\|TextFontCommand\|MathVersion\|SymbolFontAlphabet'
			    \ . '\|MathSymbol\|MathDelimiter\|MathAccent\|MathRadical\|MathOperator\)\>\|\\SetMathAlphabet\)'
	    let name=matchstr(line['text'],
			\ '\%(\\Declare\%(RobustCommand\|FixedFont\|TextFontCommand\|MathVersion\|SymbolFontAlphabet'
			    \ . '\|MathSymbol\|MathDelimiter\|MathAccent\|MathRadical\|MathOperator\)\|\\SetMathAlphabet\)\s*{\s*\zs[^}]*\ze\s*}')
	    let type="Commands"
	elseif line['text'] =~ '^[^%]*\%(\\newenvironment\|\\newtheorem\)'
	    " environment name
	    let name=matchstr(line['text'],
			\ '^[^%]*\\\%(newtheorem\*\?\|newenvironment\)\s*{\s*\zs[^}]*\ze\s*}')
	    let type="Environments"
	endif
	if exists("name") && name != '' && name != '\'
	    if count(atp_Local{type}, name) == 0
		call add(atp_Local{type}, name)
	    endif
	endif
    endfor

    let b:atp_LocalCommands		= atp_LocalCommands
    let b:atp_LocalEnvironments		= atp_LocalEnvironments
    let b:atp_LocalColors		= atp_LocalColors
    return [ atp_LocalEnvironments, atp_LocalCommands, atp_LocalColors ]

endfunction "}}}
" {{{ atplib#search#LocalCommands_py
function! atplib#search#LocalCommands_py(write, ...)
    let time=reltime()
    " The first argument pattern is not implemented
    " but it should be a python regular expression
    let bang	= a:0 >= 2 ? a:2 : '' 

    let atp_MainFile	= atplib#FullPath(b:atp_MainFile)
    let pwd		= getcwd()
    try
	exe "lcd ".fnameescape(b:atp_ProjectDir)
    catch /E344:/
	return
    endtry

"     if a:write
" 	call atplib#write("nobackup")
"     endif


    " Makeing lists of commands and environments found in input files
    if bang == "!" || !exists("b:TreeOfFiles")
	 " Update the cached values:
	 let [ b:TreeOfFiles, b:ListOfFiles, b:TypeDict, b:LevelDict ] = TreeOfFiles(atp_MainFile)
     endif
     let [ Tree, List, Type_Dict, Level_Dict ] = deepcopy([ b:TreeOfFiles, b:ListOfFiles, b:TypeDict, b:LevelDict ])

     " Note: THIS CODE IS ONLY NEEDED WHEN PWD is different than the TreeOfFiles was
     " called! There is an option to store full path in ATP, then this is not needed.
     let files = []
     for file in b:ListOfFiles
	 if get(b:TypeDict, file, "") == "input" || get(b:TypeDict, file, "") == "preambule" 
	     if filereadable(file)
		 call add(files, atplib#FullPath(file))
	     else
                 " This makes it really slow when the files are missing.
		 let file=atplib#search#KpsewhichFindFile("tex", file)
		 if file != ""
		     call add(files, file)
		 endif
	     endif
	 endif
     endfor
python << END
import re, vim, os.path

def bufnumber(file):
    for buffer in vim.buffers:
        # This requires that we are in the directory of the main tex file,
        # and the directory is changed in the vim script above.
        if buffer.name == os.path.abspath(file):
            return buffer.number
    for buffer in vim.buffers:
	try:
            if os.path.basename(buffer.name) == file:
                return buffer.number
        except:
            pass
    return 0

pattern=re.compile('\s*(?:\\\\(?P<def>def)(?P<def_c>\\\\[^#{]*)|(?:\\\\(?P<nc>newcommand)|\\\\(?P<env>newenvironment)|\\\\(?P<nt>newtheorem\*?)|\\\\(?P<col>definecolor)|\\\\(?P<dec>Declare)(?:RobustCommand|FixedFont|TextFontCommand|MathVersion|SymbolFontAlphabet|MathSymbol|MathDelimiter|MathAccent|MathRadical|MathOperator)\s*{|\\\\(?P<sma>SetMathAlphabet))\s*{(?P<arg>[^}]*)})')

files=[vim.eval("atp_MainFile")]+vim.eval("files")
localcommands   =[]
localcolors     =[]
localenvs       =[]
for file in files:
    lnr=1
    bufnr = bufnumber(file)
    if os.path.exists(file) or bufnr in vim.buffers:
        try:
            if bufnr in vim.buffers:
                file_l = vim.buffers[bufnr]
            else:
                file_ob=open(file, 'r')
                file_l=file_ob.read().split("\n")
                file_ob.close()
            for line in file_l:
                m=re.match(pattern, line)
                if m:
                    if m.group('def'):
                        if re.search('\\\\def\\\\\w+#[1-9]', line):
                            localcommands.append(m.group('def_c')+'{')
                        else:
                            localcommands.append(m.group('def_c'))
                    elif m.group('nc') or m.group('dec') or m.group('sma'):
                        if re.search('\\\\newcommand\s*{[^}]*}\s*\[[1-9]\]\s*{', line):
                            localcommands.append(m.group('arg')+'{')
                        else:
                            localcommands.append(m.group('arg'))
                    elif m.group('nt') or m.group('env'):
                        localenvs.append(m.group('arg'))
                    elif m.group('col'):
                        localcolors.append(m.group('arg'))
        except IOError:
            pass
vim.command("let atp_LocalCommands="+str(localcommands))
vim.command("let atp_LocalEnvironments="+str(localenvs))
vim.command("let atp_LocalColors="+str(localcolors))
END
if exists("atp_LocalCommands")
    let b:atp_LocalCommands=map(atp_LocalCommands, 'substitute(v:val, ''\\\\'', ''\'', '''')')
else
    let b:atp_LocalCommands=[]
endif
if exists("atp_LocalColors")
    let b:atp_LocalColors=map(atp_LocalColors, 'substitute(v:val, ''\\\\'', ''\'', '''')')
else
    let b:atp_LocalColors=[]
endif
if exists("atp_LocalEnvironments")
    let b:atp_LocalEnvironments=map(atp_LocalEnvironments, 'substitute(v:val, ''\\\\'', ''\'', '''')')
else
    let b:atp_LocalEnvironments=[]
endif
exe "lcd ".fnameescape(pwd)
let g:time_LocalCommands_py=reltimestr(reltime(time))
return [ b:atp_LocalEnvironments, b:atp_LocalCommands, b:atp_LocalColors ]
endfunction
"}}}
" atplib#search#LocalAbbreviations {{{
function! atplib#search#LocalAbbreviations()
    if !exists("b:atp_LocalEnvironments")
	let no_abbrev= ( exists('g:atp_no_local_abbreviations') ? g:atp_no_local_abbreviations : -1 )
	let g:atp_no_local_abbreviations = 1
	call LocalCommands(0)
	if no_abbrev == -1
	    unlet g:atp_no_local_abbreviations
	else
	    let g:atp_no_local_abbreviations = no_abbrev
	endif
    endif
    if exists("b:atp_LocalEnvironments")
	for env in b:atp_LocalEnvironments
	    if !empty(maparg(g:atp_iabbrev_leader.env.g:atp_iabbrev_leader, "i", 1))
	" 	silent echomsg "abbreviation " . g:atp_iabbrev_leader.env.g:atp_iabbrev_leader . " exists."
		continue
	    endif
	    if exists("g:atp_abbreviate_".env)
		execute "iabbrev <buffer> ".g:atp_iabbrev_leader.env.g:atp_iabbrev_leader." \\begin{".env."}".get(g:atp_abbreviate_{env}, 0, "<CR>")."\\end{".env."}".get(g:atp_abbreviate_{env}, 1, "<Esc>O")
	    else
		execute "iabbrev <buffer> ".g:atp_iabbrev_leader.env.g:atp_iabbrev_leader." \\begin{".env."}<CR>\\end{".env."}<Esc>O"
	    endif
	endfor
    endif
endfunction "}}}

" Search for Definition in the definition dictionary (atplib#search#make_defi_dict).
"{{{ atplib#search#Dsearch
function! atplib#search#Dsearch(bang,...)

    call atplib#write("nobackup")

    let time		= reltime()
    let o_pattern	= a:0 >= 1 ? matchstr(a:1, '\/\=\zs.*[^\/]\ze\/\=') : ''
    let pattern		= '\%(\\def\|\\\%(re\)\=newcommand\s*{\=\|\\providecommand\s*{\=\|\\\%(re\)\=newenvironment\s*{\|\\\%(re\)\=newtheorem\s*{\|\\definecolor\s*{\)\s*\\\=\w*\zs'.o_pattern
    let preambule_only	= ( a:bang == "!" ? 0 : 1 )
    let atp_MainFile	= atplib#FullPath(b:atp_MainFile)

    if has("python")
	let defi_dict	= atplib#search#make_defi_dict_py(a:bang, atp_MainFile, pattern)
    else
	let defi_dict	= atplib#search#make_defi_dict_vim(a:bang, atp_MainFile, pattern)
    endif

    if len(defi_dict) > 0
	" wipe out the old buffer and open new one instead
	if bufloaded("DefiSearch")
	    exe "silent bw! " . bufnr("DefiSearch") 
	endif
	if !exists("b:atp_MainFile") || !exists("b:atp_ProjectDir")
	    " Note: I should write a function to read just one variable from
	    " project file.
	    LoadProjectScript
	endif
	setl syntax=tex

	let defi_list 	= []
	let signs	= []

	for inputfile in keys(defi_dict)
	    let ifile	= readfile(inputfile)
	    for l:range in defi_dict[inputfile]
		" This respects the options 'smartcase' and 'ignorecase'.
		let case = ( &l:smartcase && &l:ignorecase && pattern =~ '\u' ? 'noignorecase'  : ( &l:ignorecase ? 'ignorecase' : 'noignorecase' )) 
		let condition = ( case == "noignorecase" ? ifile[l:range[0]-1] =~# pattern : ifile[l:range[0]-1] =~? pattern )
		if condition
		    " print the lines into defi_list
		    let i=0
		    let c=0
		    " add an empty line if the definition is longer than one line
		    if l:range[0] != l:range[1]
			call add(defi_list, '')
			let i+=1
		    endif
		    while c <= l:range[1]-l:range[0] 
			let line=l:range[0]+c
			call add(defi_list, ifile[line-1])
			if c == 0 
			    let cmd = matchstr(ifile[line-1], '\\\%(def\|\%(re\)\?newcommand\s*{\|providecommand\s*{\|\%(re\)\?newenvironment\s*{\|\%(re\)\?newtheorem\s*{\|definecolor\s*{\)\zs[^ {}#]*\ze')
			    call add(signs, [len(defi_list), cmd])
			endif
			let i+=1
			let c+=1
		    endwhile
		endif
	    endfor
	endfor

	if len(defi_list) == 0
	    redraw
	    echohl ErrorMsg
	    if a:bang == "!"
		echomsg "[ATP:] definition not found."
	    else
		echomsg "[ATP:] definition not found in the preambule, try with a bang ! to search beyond."
	    endif
	    echohl None
	    return
	endif

	" open new buffer
	let window_height= min([g:atp_DsearchMaxWindowHeight, len(defi_list)])
	let openbuffer=" +setl\\ buftype=nofile\\ nospell\\ nornu\\ nonu\\ mod\\ noswf\\ nobl\\ bh=wipe " . fnameescape("DefiSearch")
	if g:vertical == 1
	    let openbuffer="keepalt vsplit " . openbuffer 
	else
	    let openbuffer="keepalt rightbelow ".window_height."split " . openbuffer 
	endif
	silent exe openbuffer
	let &l:statusline="Dsearch: ".o_pattern

	call setline(1, defi_list)
	if getline(line(".")) =~ '^\s*$'
	    normal! dd
	    call map(signs, '[v:val[0]-1,v:val[1]]')
	endif
	if o_pattern != ""
	    call matchadd('Search', ( &l:ignorecase ? '\c' : '\C' ) .o_pattern)
	    let @/=o_pattern
	endif
	setl syntax=tex
	setl readonly
	map <buffer> <silent> q	:bd<CR>
	" Place signs:
	if has("signs")
	    sign unplace *
	    for i in range(0,len(signs)-1)
		try
		    exe 'sign define '.signs[i][1].' text=>>'
		    exe 'sign place '.(i+1).' line='.signs[i][0].' name='.signs[i][1].' file='.expand('%:p')
		catch /E474/
		    if g:atp_devversion
			echoerr "[signs:] ".'sign place '.(i+1).' line='.signs[i][0].' name='.signs[i][1].' file='.expand('%:p')
		    endif
		endtry
	    endfor
	endif
    else
	redraw
	echohl ErrorMsg
	if a:bang == "!"
	    echomsg "[ATP:] definition not found."
	else
	    echomsg "[ATP:] definition not found in the preambule, try with a bang ! to search beyond."
	endif
	echohl None
    endif
    setl nomodifiable

    let g:source_time_DSEARCH=reltimestr(reltime(time))
endfunction
function! atplib#search#DsearchComp(ArgLead, CmdLine, CursorPos)
    if !exists("b:atp_LocalCommands")
        LocalCommands
    endif
    let list=[]
    call extend(list, b:atp_LocalCommands)
    call extend(list, b:atp_LocalColors)
    call extend(list, b:atp_LocalEnvironments)
    call filter(list, 'v:val =~ a:ArgLead')
    call map(list, 'escape(v:val, ''\*'')')
    return sort(list)
endfunction
"}}}

" Search in tree and return the one level up element and its line number.
" {{{ atplib#search#SearchInTree
" Before running this function one has to set the two variables
" s:branch/s:branch_line to 0.
" the a:tree variable should be something like:
" a:tree = { b:atp_MainFile, [ TreeOfFiles(b:atp_MainFile)[0], 0 ] }
" necessary a rooted tree!

" This function remaps keys of dictionary.
function! atplib#search#MapDict(dict) 
    let new_dict = {}
    for key in keys(a:dict)
	let new_key = fnamemodify(key, ":p")
	let new_dict[new_key] = a:dict[key] 
    endfor
    return new_dict
endfunction

function! atplib#search#SearchInTree(tree, branch, what)
    if g:atp_debugSIT
	exe "redir! > ".g:atp_TempDir."/SearchInTree.log"
	silent! echo "___SEARCH_IN_TREE___"
	silent! echo "a:branch=". a:branch
	silent! echo "a:what=" . a:what
    endif
    if g:atp_debugSIT >= 2
	silent! echo "a:tree=" . string(a:tree)
    endif
	
"     let branch	= a:tree[a:branch][0]
    if a:branch =~ '^\s*\/'
	let cwd		= getcwd()
	exe "lcd " . fnameescape(b:atp_ProjectDir)
	let branchArg	= ( g:atp_RelativePath 	? fnamemodify(a:branch, ":.") 	: a:branch  )
	let branchArgN	= ( !g:atp_RelativePath ? fnamemodify(a:branch, ":.") 	: a:branch  )
	let whatArg	= ( g:atp_RelativePath 	? fnamemodify(a:what, ":.") 	: a:what  )
	let whatArgN	= ( !g:atp_RelativePath ? fnamemodify(a:what, ":.") 	: a:what  )
	if g:atp_debugSIT
	    silent! echo "*** cwd=" . getcwd() . " b:atp_ProjectDir= " . b:atp_ProjectDir . " " . fnamemodify(a:branch, ":.") . " " . a:branch
	endif
	exe "lcd " . fnameescape(cwd)
    else
	let branchArg	= ( g:atp_RelativePath 	? a:branch 	: atplib#FullPath(a:branch) )
	let branchArgN	= ( !g:atp_RelativePath ? a:branch 	: atplib#FullPath(a:branch) )
	let whatArg	= ( g:atp_RelativePath 	? a:what 	: atplib#FullPath(a:what) )
	let whatArgN	= ( !g:atp_RelativePath ? a:what 	: atplib#FullPath(a:what) )
    endif
    if g:atp_debugSIT
	silent! echo "branchArg=" . branchArg . " branchArgN=" . branchArgN
	silent! echo "whatArg=" . whatArg . " whatArgN=" . whatArgN
    endif
    let branch	= get(a:tree, branchArg , get(a:tree, branchArgN, ['NO_BRANCH']))[0]
    if count(keys(branch), whatArg) || count(keys(branch), whatArgN)
	" The following variable is used as a return value in
	" RecursiveSearch!
	let g:ATP_branch	= branchArg
	let g:ATP_branch_line	= get(branch, whatArg, get(branch, whatArgN, ['', 'ERROR']))[1]
	if g:atp_debugSIT
	    silent! echo "g:ATP_branch=" . g:ATP_branch . "   g:ATP_branch_line=" . g:ATP_branch_line
	    redir END
	endif
	return branchArg
    else
	for new_branch in keys(branch)
	    call atplib#search#SearchInTree(branch, new_branch, whatArg)
	endfor
    endif
    if g:atp_debugSIT
	redir END
    endif
    return
endfunction
" }}}

" Search in all input files recursively.
" {{{ __Recursive_Search__
"
" Variables are used to pass them to next runs (this function calls it self) 
" a:main_file	= b:atp_MainFile
" a:start_file	= expand("%:p") 	/this variable will not change untill the
" 						last instance/ 
" a:tree	= make_tree 		=> make a tree
" 		= any other value	=> use { a:main_file : [ b:TreeOfFiles, 0] }	
" a:cur_branch	= expand("%") 		/this will change whenever we change a file/
" a:call_nr	= number of the call			
" a:wrap_nr	= if hit top/bottom a:call=0 but a:wrap_nr+=1
" a:winsaveview = winsaveview(0)  	to resotre the view if the pattern was not found
" a:bufnr	= bufnr("%")		to come back to begining buffer if pattern not found
" a:strftime	= strftime(0)		to compute the time
" a:pattern	= 			pattern to search
" a:1		=			flags: 'bcewWs'
" a:2 is not not used:
" a:2		= 			goto = DOWN_ACCEPT / Must not be used by the end user/
" 					0/1 1=DOWN_ACCEPT	
" 								
" g:atp_debugRS 	if 1 sets debugging messages which are appended to '/tmp/ATP_rs_debug' 
			" you can :set errorfile=/tmp/ATP_rs_debug
			" and	  :set efm=.*
			" if 2 show time
" log file : /tmp/ATP_rs_debug
" {{{ atplib#search#RecursiveSearch function
try
function! atplib#search#RecursiveSearch(main_file, start_file, maketree, tree, cur_branch, call_nr, wrap_nr, winsaveview, bufnr, strftime, vim_options, cwd, pattern, subfiles, ... )

    let main_file	= g:atp_RelativePath ? atplib#RelativePath(a:main_file, b:atp_ProjectDir) : a:main_file
	
    let time0	= reltime()

    " set and restore some options:
    " foldenable	(unset to prevent opening the folds :h winsaveview)
    " comeback to the starting buffer
    if a:call_nr == 1 && a:wrap_nr == 1

	" Erease message 'search hit TOP, continuing at BOTTOM':
	if &shortmess =~# 's'
	    echo ""
	endif

	if a:vim_options	== { 'no_options' : 'no_options' }
	    let vim_options 	=  { 'hidden'	: &l:hidden, 
				\ 'foldenable' 	: &l:foldenable,
				\ 'autochdir'	: &l:autochdir }
	else
	    let vim_options	= a:vim_options
	endif
	let &l:hidden		= 1
	let &l:foldenable	= 0
	let &l:autochdir	= 0

	if a:cwd		== 'no_cwd'
	    let cwd		=  getcwd()
	else
	    let cwd		= a:cwd
	endif
	exe "lcd " . fnameescape(b:atp_ProjectDir)

	" This makes it work faster when the input files were not yet opened by vim 
	" some of them will not be shown to the user.
	" Note: but sometimes files are loaded without filetype what messes up
	" things. It is possible to make it work I think, but this might not
	" be needed (speed seems to be fine).
" 	syntax off
	set eventignore+=Syntax
" 	filetype off 
	" there are many errors in /tmp/ATP_rs_debug file due to this which are not
	" important.

    else
	let vim_options		= a:vim_options
	let cwd			= a:cwd
    endif

    let subfiles = ( a:subfiles == "" ? atplib#search#SearchPackage('subfiles') : a:subfiles )

	    " Redirect debuggin messages:
	    if g:atp_debugRS
		if a:wrap_nr == 1 && a:call_nr == 1
		    exe "redir! > ".g:atp_TempDir."/RecursiveSearch.log"
		else
		    exe "redir! >> ".g:atp_TempDir."/RecursiveSearch.log"
		endif
		silent echo "________________"
		silent echo "Args: a:pattern:".a:pattern." call_nr:".a:call_nr. " wrap_nr:".a:wrap_nr . " cwd=" . getcwd()
	    endif

    	let flags_supplied = a:0 >= 1 ? a:1 : ""

	if flags_supplied =~# 'p'
	    let flags_supplied = substitute(flags_supplied, 'p', '', 'g')
	    echohl WarningMsg
	    echomsg "[ATP:] searching flag 'p' is not supported, filtering it out."
	    echohl None
	endif

	if a:maketree == 'make_tree'
	    if g:atp_debugRS
	    silent echo "*** Makeing Tree ***"
	    endif
	    let tree_of_files 	= TreeOfFiles(main_file)[0]
	else
	    if g:atp_debugRS
	    silent echo "*** Using Tree ***"
	    endif
	    let tree_of_files	= a:tree
	endif
	let tree	= { main_file : [ tree_of_files, 0 ] }

	if a:cur_branch != "no cur_branch "
	    let cur_branch	= a:cur_branch
	else
	    let cur_branch	= main_file
	endif

		if g:atp_debugRS > 1
		    silent echo "TIME0:" . reltimestr(reltime(time0))
		endif

	let pattern		= a:pattern
	let flags_supplied	= substitute(flags_supplied, '[^bcenswWS]', '', 'g')

    	" Add pattern to the search history
	if a:call_nr == 1
	    call histadd("search", a:pattern)
	    let @/ = a:pattern
	endif

	" Set up searching flags
	let flag	= flags_supplied
	if a:call_nr > 1 
	    let flag	= flags_supplied !~# 'c' ? flags_supplied . 'c' : flags_supplied
	endif
	let flag	= substitute(flag, 'w', '', 'g') . 'W'
	let flag	= flag !~# 'n' ? substitute(flag, 'n', '', 'g') . 'n' : flag
	let flag	= substitute(flag, 's', '', 'g')

	if flags_supplied !~# 'b'
	    " forward searching flag for input files:
	    let flag_i	= flags_supplied !~# 'c' ? flags_supplied . 'c' : flags_supplied
	else
	    let flag_i	= substitute(flags_supplied, 'c', '', 'g')
	endif
	let flag_i	= flag_i !~# 'n' ? flag_i . 'n' : flag_i
	let flag_i	= substitute(flag_i, 'w', '', 'g') . 'W'
	let flag_i	= substitute(flag_i, 's', '', 'g')

		if g:atp_debugRS
		silent echo "      flags_supplied:".flags_supplied." flag:".flag." flag_i:".flag_i." a:1=".(a:0 != 0 ? a:1 : "")
		endif

	" FIND PATTERN: 
	let cur_pos		= [line("."), col(".")]
	" We filter out the 's' flag which should be used only once
	" as the flags passed to next atplib#search#RecursiveSearch()es are based on flags_supplied variable
	" this will work.
	let s_flag		= flags_supplied =~# 's' ? 1 : 0
	let flags_supplied	= substitute(flags_supplied, 's', '', 'g')
	if s_flag
	    call setpos("''", getpos("."))
	endif
	keepjumps let pat_pos	= searchpos(pattern, flag)

		if g:atp_debugRS > 1
		    silent echo "TIME1:" . reltimestr(reltime(time0))
		endif

	" FIND INPUT PATTERN: 
	" (we do not need to search further than pat_pos)
	if pat_pos == [0, 0]
	    let stop_line	= flag !~# 'b' ? line("$")  : 1
	else
	    let stop_line	= pat_pos[0]
	endif
	if subfiles
	    keepjumps let input_pos	= searchpos('^[^%]*\\\(input\|include\|subfile\)\s*{', flag_i . 'n', stop_line )
	else
	    keepjumps let input_pos	= searchpos('^[^%]*\\\(input\|include\)\s*{', flag_i . 'n', stop_line )
	endif

		if g:atp_debugRS > 1
		    silent echo "TIME2:" . reltimestr(reltime(time0))
		endif

		if g:atp_debugRS
		silent echo "Positions: ".string(cur_pos)." ".string(pat_pos)." ".string(input_pos)." in branch: ".cur_branch."#".expand("%:p") . " stop_line: " . stop_line 
		endif


	" Down Accept:
	" the current value of down_accept
	let DOWN_ACCEPT = a:0 >= 2 ? a:2 : 0
	" the value of down_accept in next turn 
	let down_accept	= getline(input_pos[0]) =~ pattern || input_pos == [0, 0] ?  1 : 0

" 		if g:atp_debugRS
" 		    silent echo "DOWN_ACCEPT=" . DOWN_ACCEPT . " down_accept=" . down_accept
" 		endif

	" Decide what to do: accept the pattern, go to higher branch, go to lower
	" branch or say Pattern not found
	if flags_supplied !~# 'b'
	    " FORWARD
	    " cur < pat <= input
	    if atplib#CompareCoordinates(cur_pos,pat_pos) && atplib#CompareCoordinates_leq(pat_pos, input_pos)
		let goto_s	= 'ACCEPT'
	    " cur == pat <= input
	    elseif cur_pos == pat_pos && atplib#CompareCoordinates_leq(pat_pos, input_pos)
		" this means that the 'flag' variable has to contain 'c' or the
		" wrapscan is on
		" ACCEPT if 'c' and wrapscan is off or there is another match below,
		" if there is not go UP.
		let wrapscan	= ( flags_supplied =~# 'w' || &l:wrapscan && flags_supplied !~# 'W' )
		if flag =~# 'c'
		let goto_s	= 'ACCEPT'
		elseif wrapscan
		    " if in wrapscan and without 'c' flag
		let goto_s	= 'UP'
		else
		    " this should not happen: cur == put can hold only in two cases:
		    " wrapscan is on or 'c' is used.
		    let goto_s	= 'ERROR'
		endif
	    " pat < cur <= input
	    elseif atplib#CompareCoordinates(pat_pos, cur_pos) && atplib#CompareCoordinates_leq(cur_pos, input_pos) 
		let goto_s	= 'UP'
	    " cur < input < pat
	    elseif atplib#CompareCoordinates(cur_pos, input_pos) && atplib#CompareCoordinates(input_pos, pat_pos)
		let goto_s	= 'UP'
	    " cur < input == pat 		/we are looking for '\\input'/
	    elseif atplib#CompareCoordinates(cur_pos, input_pos) && input_pos == pat_pos
		let goto_s	= 'ACCEPT'
	    " input < cur <= pat	(includes input = 0])
	    elseif atplib#CompareCoordinates(input_pos, cur_pos) && atplib#CompareCoordinates_leq(cur_pos, pat_pos)
		" cur == pat thus 'flag' contains 'c'.
		let goto_s	= 'ACCEPT'
	    " cur == input
	    elseif cur_pos == input_pos
		let goto_s	= 'UP'
	    " cur < input < pat
	    " input == 0 			/there is no 'input' ahead - flag_i contains 'W'/
	    " 					/but there is no 'pattern ahead as well/
	    " at this stage: pat < cur 	(if not then  input = 0 < cur <= pat was done above).
	    elseif input_pos == [0, 0]
		if expand("%:p") == fnamemodify(main_file, ":p")
		    " wrapscan
		    if ( flags_supplied =~# 'w' || &l:wrapscan  && flags_supplied !~# 'W' )
			let new_flags	= substitute(flags_supplied, 'w', '', 'g') . 'W'  
			if a:wrap_nr <= 2
			    call cursor(1,1)

				if g:atp_debugRS
				silent echo " END 1 new_flags:" . new_flags 
				redir END
				endif

			    keepjumps call atplib#search#RecursiveSearch(main_file, a:start_file, "", tree_of_files, a:cur_branch, 1, a:wrap_nr+1, a:winsaveview, a:bufnr, a:strftime, vim_options, cwd, pattern, subfiles, new_flags) 

			    return
			else
			    let goto_s 	= "REJECT"
" 			    echohl ErrorMsg
" 			    echomsg 'Pattern not found: ' . a:pattern
" 			    echohl None
			endif
		    else
			let goto_s 	= "REJECT"
" 			echohl ErrorMsg
" 			echomsg 'Pattern not found: ' . a:pattern
" 			echohl None
		    endif
		" if we are not in the main file go up.
		else
		    let goto_s	= "DOWN"
		endif
	    else
		let goto_s 	= 'ERROR'
	    endif
	else
	    " BACKWARD
	    " input <= pat < cur (pat != 0)
	    if atplib#CompareCoordinates(pat_pos, cur_pos) && atplib#CompareCoordinates_leq(input_pos, pat_pos) && pat_pos != [0, 0]
		" input < pat
		if input_pos != pat_pos
		    let goto_s	= 'ACCEPT'
		" input == pat
		else
		    let goto_s	= 'UP'
		endif
	    " input <= pat == cur (input != 0)			/pat == cur => pat != 0/
	    elseif cur_pos == pat_pos && atplib#CompareCoordinates_leq(input_pos, pat_pos) && input_pos != [0, 0]
		" this means that the 'flag' variable has to contain 'c' or the
		" wrapscan is on
		let wrapscan	= ( flags_supplied =~# 'w' || &l:wrapscan  && flags_supplied !~# 'W' )
		if flag =~# 'c'
		    let goto_s 	= 'ACCEPT'
		elseif wrapscan
		    " if in wrapscan and without 'c' flag
		    let goto_s	= 'UP'
		else
		    " this should not happen: cur == put can hold only in two cases:
		    " wrapscan is on or 'c' is used.
		    let goto_s	= 'ERROR'
		endif
	    " input <= cur < pat (input != 0)
	    elseif atplib#CompareCoordinates(cur_pos, pat_pos) && atplib#CompareCoordinates_leq(input_pos, cur_pos) && input_pos != [0, 0] 
		let goto_s	= 'UP'
	    " pat < input <= cur (input != 0)
	    elseif atplib#CompareCoordinates_leq(input_pos, cur_pos) && atplib#CompareCoordinates(pat_pos, input_pos) && input_pos != [0, 0]
		let goto_s	= 'UP'
	    " input == pat < cur (pat != 0) 		/we are looking for '\\input'/
	    elseif atplib#CompareCoordinates(input_pos, cur_pos) && input_pos == pat_pos && pat_pos != [0, 0]
		let goto_s	= 'ACCEPT'
	    " pat <= cur < input (pat != 0) 
	    elseif atplib#CompareCoordinates(cur_pos, input_pos) && atplib#CompareCoordinates_leq(pat_pos, cur_pos) && input_pos != [0, 0]
		" cur == pat thus 'flag' contains 'c'.
		let goto_s	= 'ACCEPT'
	    " cur == input
	    elseif cur_pos == input_pos
		let goto_s 	= 'UP'
	    " input == 0 			/there is no 'input' ahead - flag_i contains 'W'/
	    " 					/but there is no 'pattern ahead as well/
	    " at this stage: cur < pat || pat=input=0  (if not then  pat <= cur was done above, input=pat=0 is the 
	    " 						only posibility to be passed by the above filter).
	    elseif input_pos == [0, 0]
		" I claim that then cur < pat or pat=0
		if expand("%:p") == fnamemodify(main_file, ":p")
		    " wrapscan
		    if ( flags_supplied =~# 'w' || &l:wrapscan  && flags_supplied !~# 'W' )
			let new_flags	= substitute(flags_supplied, 'w', '', 'g') . 'W'  
			if a:wrap_nr <= 2
			    call cursor(line("$"), col("$"))

				if g:atp_debugRS
				silent echo " END 2 new_flags:".new_flags
				redir END
				endif

			    keepjumps call atplib#search#RecursiveSearch(main_file, a:start_file, "", tree_of_files, a:cur_branch, 1, a:wrap_nr+1, a:winsaveview, a:bufnr, a:strftime, vim_options, cwd, pattern, subfiles, new_flags) 

				if g:atp_debugRS > 1
				    silent echo "TIME_END:" . reltimestr(reltime(time0))
				endif

			    return
			else
			    let goto_s 	= "REJECT"
" 			    echohl ErrorMsg
" 			    echomsg 'Pattern not found: ' . a:pattern
" 			    echohl None
			endif
		    else
			let goto_s 	= "REJECT"
		    endif
		" if we are not in the main file go up.
		else
		    let goto_s	= "DOWN" 
		    " If using the following line DOWN_ACCEPT and down_accept
		    " variables are not needed. This seems to be the best way.
		    " 	There is no need to use this feature for
		    " 	\input <file_name> 	files.
		    if pattern =~ '\\\\input' || pattern =~ '\\\\include' || pattern =~ '\\\\subfile'
" 			if getline(input_pos[0]) =~ pattern || getline(".") =~ pattern
			let goto_s	= "DOWN_ACCEPT"
		    endif
		endif
	    else
		let goto_s 	= 'ERROR'
	    endif
	endif

		if g:atp_debugRS
		silent echo "goto_s:".goto_s
		endif
		if g:atp_debugRS >= 2
		    silent echo "TIME ***goto*** " . reltimestr(reltime(time0))
		endif

	" When ACCEPTING the line:
	if goto_s == 'ACCEPT'
	    keepjumps call setpos(".", [ 0, pat_pos[0], pat_pos[1], 0])
	    if flags_supplied =~#  'e'
		keepjumps call search(pattern, 'e', line("."))
	    endif
	    "A Better solution must be found.
" 	    if &l:hlsearch
" 		execute '2match Search /'.pattern.'/'
" 	    endif
		
	    let time	= matchstr(reltimestr(reltime(a:strftime)), '\d\+\.\d\d\d') . "sec."

	    if &shortmess =~# 's'
		if a:wrap_nr == 2 && flags_supplied =~# 'b'
		    redraw
		    echohl WarningMsg
		    echo "search hit TOP, continuing at BOTTOM "
		    echohl None
		elseif a:wrap_nr == 2
		    redraw
		    echohl WarningMsg
		    echo "search hit BOTTOM, continuing at TOP "
		    echohl None
		endif
	    endif

		if g:atp_debugRS
		silent echo "FOUND PATTERN: " . a:pattern . " time " . time
		silent echo ""
		redir END
		endif

		" restore vim options 
		if a:vim_options != { 'no_options' : 'no_options' }
		    for option in keys(a:vim_options)
			execute "let &l:".option."=".a:vim_options[option]
		    endfor
		endif
		exe "lcd " . fnameescape(cwd)
		set eventignore-=Syntax
		syntax enable
" 		filetype on
" 		filetype detect

	    return

	" when going UP
	elseif goto_s == 'UP'
	    call setpos(".", [ 0, input_pos[0], input_pos[1], 0])
	    " Open file and Search in it"
	    " This should be done by kpsewhich:
	    if subfiles
		let file = matchstr(getline(input_pos[0]), '\\\(input\|subfile\|include\)\s*{\zs[^}]*\ze}')
	    else
		let file = matchstr(getline(input_pos[0]), '\\\(input\|include\)\s*{\zs[^}]*\ze}')
	    endif
	    if g:atp_debugRS
		silent echo " ------ file=".file." ".getline(input_pos[0])
		silent echo " ------ input_pos=".string(input_pos)
	    endif
	    let file = atplib#append_ext(file, '.tex')

	    let keepalt = ( @# == '' || expand("%:p") == a:start_file ? '' : 'keepalt' )
	    let open =  flags_supplied =~ 'b' ? keepalt . ' edit + ' : keepalt.' edit +1 '
	    let swapfile = globpath(fnamemodify(file, ":h"), ( has("unix") ? "." : "" ) . fnamemodify(file, ":t") . ".swp")

	    if !( a:call_nr == 1 && a:wrap_nr == 1 )
		let open = "silent keepjumps " . open
	    endif

	    let projectVarDict 	= SaveProjectVariables()
	    if g:atp_debugRS >= 3
		silent echo "projectVarDict : " . string(projectVarDict) 
		let g:projectVarDict = projectVarDict
	    elseif g:atp_debugRS >= 2
		let g:projectVarDict = projectVarDict
	    endif
	    if g:atp_debugRS >= 2
		silent echo "TIME ***goto UP before open*** " . reltimestr(reltime(time0))
	    endif

" ERROR: When opening for the first time there are two errors which
" I cannot figure out.

	    " OPEN:
	    if empty(swapfile) || bufexists(file)
		if g:atp_debugRS >= 2
		silent echo "Alternate (before open) " . bufname("#")
		silent echo " XXXXXXXX file=".file
		endif
		" silent should not have bang, which prevents E325 to be shown.
		silent execute open . fnameescape(file)
		if g:atp_mapNn
		    call atplib#search#ATP_ToggleNn(1,"on")
		else
		    call atplib#search#ATP_ToggleNn(1,"off")
		endif
" 		if &l:filetype != "tex"
" 		    setl filetype=tex
" 		endif
	    else
		echoerr "Recursive Search: swap file: " . swapfile . " exists. Aborting." 
		set eventignore-=Syntax
		syntax enable
		return
	    endif
	    if g:atp_debugRS >= 2
		exe "redir! >> ".g:atp_TempDir."/RecursiveSearch.log"
		silent echo "TIME ***goto UP after open*** " . reltimestr(reltime(time0))
	    endif

	    call RestoreProjectVariables(projectVarDict)
	    if g:atp_debugRS >= 2
		silent echo "TIME ***goto UP restore variables *** " . reltimestr(reltime(time0))
	    endif

	    if flags_supplied =~# 'b'
		call cursor(line("$"), col("$"))
	    else
		call cursor(1,1)
	    endif

		if g:atp_debugRS
		silent echo "In higher branch:      " . file . " POS " line(".").":".col(".") 
		silent echo "Open Command:          '" . open . file . "'"
		silent echo "exist b:TreeOfFiles    " . exists("b:TreeOfFiles")
		silent echo "flags_supplied:        " . flags_supplied
		endif
		if g:atp_debugRS >= 2
		silent echo "Alternate (after open) " . bufname("#")
		endif

		if g:atp_debugRS >= 2
		silent echo "TIME_END:              " . reltimestr(reltime(time0))
		endif


	    let flag	= flags_supplied =~ 'W' ? flags_supplied : flags_supplied . 'W'
	    if @# == ''
		keepjumps call atplib#search#RecursiveSearch(main_file, a:start_file, "", tree_of_files, expand("%:p"), a:call_nr+1, a:wrap_nr, a:winsaveview, a:bufnr, a:strftime, vim_options, cwd, pattern, subfiles, flags_supplied, down_accept)
	    else
		keepalt keepjumps call atplib#search#RecursiveSearch(main_file, a:start_file, "", tree_of_files, expand("%:p"), a:call_nr+1, a:wrap_nr, a:winsaveview, a:bufnr, a:strftime, vim_options, cwd, pattern, subfiles, flags_supplied, down_accept)
	    endif

	    if g:atp_debugRS
		redir END
	    endif
	    return

	" when going DOWN
	elseif goto_s == 'DOWN' || goto_s == 'DOWN_ACCEPT'
	    " We have to get the element in the tree one level up + line number
	    let g:ATP_branch 		= "nobranch"
	    let g:ATP_branch_line	= "nobranch_line"

		if g:atp_debugRS
		silent echo "     SearchInTree Args " . expand("%:p")
		endif

	    if g:atp_RelativePath
		call atplib#search#SearchInTree(l:tree, main_file, atplib#RelativePath(expand("%:p"), resolve(b:atp_ProjectDir)))
	    else
		call atplib#search#SearchInTree(l:tree, main_file, expand("%:p"))
	    endif

		if g:atp_debugRS
		silent echo "     SearchInTree found " . g:ATP_branch . " g:ATP_branch_line=" . g:ATP_branch_line
		endif

	    if g:ATP_branch == "nobranch"
		echohl ErrorMsg
		echomsg "[ATP:] Error. Try to run :S! or :InputFiles command."
		echohl None

		silent! echomsg "Tree=" . string(l:tree)
		silent! echomsg "MainFile " . main_file . " current_file=" . expand("%:p")
		silent! echomsg "Going to file : " . g:ATP_branch . " ( g:ATP_branch ) "

	    	" restore the window and buffer!
		let keepalt = ( @# == '' || expand("%:p") == a:start_file ? '' : 'keepalt' )
		silent execute keepalt. " keepjumps edit #" . a:bufnr
		if g:atp_mapNn
		    call atplib#search#ATP_ToggleNn(1,"on")
		else
		    call atplib#search#ATP_ToggleNn(1,"off")
		endif
		call winrestview(a:winsaveview)
		if g:atp_debugRS
		    redir END
		endif

		set eventignore-=Syntax
		syntax enable
		return
	    endif

	    let next_branch = atplib#FullPath(g:ATP_branch)
	    let swapfile = globpath(fnamemodify(next_branch, ":h"), ( has("unix") ? "." : "" ) . fnamemodify(next_branch, ":t") . ".swp")
	    let keepalt = ( @# == '' || expand("%:p") == a:start_file ? '' : 'keepalt' )
	    if a:call_nr == 1 && a:wrap_nr == 1 
		let open =  'silent '.keepalt.' edit +'.g:ATP_branch_line." ".fnameescape(next_branch)
	    else
		let open =  'silent keepjumps '.keepalt.' edit +'.g:ATP_branch_line." ".fnameescape(next_branch)
	    endif

	    if g:atp_debugRS >= 2
		silent echo "TIME ***goto DOWN before open*** " . reltimestr(reltime(time0))
	    endif
	    let projectVarDict 	= SaveProjectVariables()
	    if empty(swapfile) || bufexists(next_branch)
		if g:atp_debugRS >= 2
		silent echo "Alternate (before open) " . bufname("#")
		endif
		" silent should not have bang, which prevents E325 to be shown.
		silent execute open
		if g:atp_mapNn
		    call atplib#search#ATP_ToggleNn(1,"on")
		else
		    call atplib#search#ATP_ToggleNn(1,"off")
		endif
" 		if &l:filetype != "tex"
" 		    setl filetype=tex
" 		endif
	    else
		echoerr "Recursive Search: swap file: " . swapfile . " exists. Aborting." 
		set eventignore-=Syntax
		syntax enable
		return
	    endif
	    if g:atp_debugRS >= 2
		silent echo "TIME ***goto DOWN after open*** " . reltimestr(reltime(time0))
	    endif
	    call RestoreProjectVariables(projectVarDict)
	    if g:atp_debugRS >= 2
		silent echo "TIME ***goto DOWN restore project variables *** " . reltimestr(reltime(time0))
	    endif

" 	    call cursor(g:ATP_branch_line, 1)
	    if flags_supplied !~# 'b'
		if subfiles
		    keepjumps call search('\m\\\(input\|\include\|subfile\)\s*{[^}]*}', 'e', line(".")) 
		else
		    keepjumps call search('\m\\\(input\|\include\)\s*{[^}]*}', 'e', line(".")) 
		endif
	    endif

		if g:atp_debugRS
		silent echo "In lower branch:       " . g:ATP_branch . " branch_line=" . g:ATP_branch_line. " POS " . line(".") . ":" . col(".") 
		silent echo "Open Command           '" . open . "'"
		silent echo "exist b:TreeOfFiles    " . exists("b:TreeOfFiles")
		silent echo "flags_supplied:        " . flags_supplied
		endif
		if g:atp_debugRS >= 2
		silent echo "Alternate (after open) " . bufname("#")
		endif

		if g:atp_debugRS > 1
		silent echo "TIME_END:               " . reltimestr(reltime(time0))
		endif

	    unlet g:ATP_branch
	    unlet g:ATP_branch_line
" 	    let flag	= flags_supplied =~ 'W' ? flags_supplied : flags_supplied . 'W'
	    if goto_s == 'DOWN'
		if @# == ''
		    keepjumps call atplib#search#RecursiveSearch(main_file, a:start_file, "", tree_of_files, expand("%:p"), a:call_nr+1, a:wrap_nr, a:winsaveview, a:bufnr, a:strftime, vim_options, cwd, pattern, subfiles, flags_supplied)
		else
		    keepalt keepjumps call atplib#search#RecursiveSearch(main_file, a:start_file, "", tree_of_files, expand("%:p"), a:call_nr+1, a:wrap_nr, a:winsaveview, a:bufnr, a:strftime, vim_options, cwd, pattern, subfiles, flags_supplied)
		endif
	    endif

	" when REJECT
	elseif goto_s == 'REJECT'
	    echohl ErrorMsg
	    echomsg "[ATP:] pattern not found"
	    echohl None

	    if g:atp_debugRS > 1
		silent echo "TIME_END:" . reltimestr(reltime(time0))
	    endif

" 	    restore the window and buffer!
" 		it is better to remember bufnumber
	    let keepalt = ( @# == '' || expand("%:p") == a:start_file ? '' : 'keepalt' )
	    silent execute "keepjumps ".keepalt." edit #" . a:bufnr
	    if g:atp_mapNn
		call atplib#search#ATP_ToggleNn(1,"on")
	    else
		call atplib#search#ATP_ToggleNn(1,"off")
	    endif

	    call winrestview(a:winsaveview)

		if g:atp_debugRS
		silent echo ""
		redir END
		endif

	    " restore vim options 
	    if a:vim_options != { 'no_options' : 'no_options' }
		for option in keys(a:vim_options)
		    execute "let &l:".option."=".a:vim_options[option]
		endfor
	    endif
	    exe "lcd " . fnameescape(cwd)
	    set eventignore-=Syntax
	    syntax enable
" 	    filetype on
" 	    filetype detect

	    return

	" when ERROR
	elseif
	    echohl ErrorMsg
	    echomsg "[ATP:] this is a bug in ATP."
	    echohl None
	    
	    " restore vim options 
	    if a:vim_options != { 'no_options' : 'no_options' }
		for option in keys(a:vim_options)
		    execute "let &l:".option."=".a:vim_options[option]
		endfor
	    endif
	    exe "lcd " . fnameescape(cwd)
	    set eventignore-=Syntax
" 	    filetype on
" 	    filetype detect

	    " restore the window and buffer!
	    let keepalt = ( @# == '' || expand("%:p") == a:start_file ? '' : 'keepalt' )
	    silent execute "keepjumps ".keepalt." edit #" . a:bufnr
	    if g:atp_mapNn
		call atplib#search#ATP_ToggleNn(1,"on")
	    else
		call atplib#search#ATP_ToggleNn(1,"off")
	    endif
	    call winrestview(a:winsaveview)

	    return 
	endif
endfunction
catch /E127:/  
endtry
" }}}

" User interface to atplib#search#RecursiveSearch function.
" atplib#search#GetSearchArgs {{{
" This functionn returns arguments from <q-args> - a list [ pattern, flag ]
" It allows to pass arguments to atplib#search#Search in a similar way to :vimgrep, :ijump, ... 
function! atplib#search#GetSearchArgs(Arg,flags)
    let g:Arg = a:Arg
    if a:Arg =~ '^\/'
	let pattern 	= matchstr(a:Arg, '^\/\zs.*\ze\/')
	let flag	= matchstr(a:Arg, '\/.*\/\s*\zs['.a:flags.']*\ze\s*$')
    elseif a:Arg =~ '^\i' && a:Arg !~ '^\w'
	let pattern 	= matchstr(a:Arg, '^\(\i\)\zs.*\ze\1')
	let flag	= matchstr(a:Arg, '\(\i\).*\1\s*\zs['.a:flags.']*\ze\s*$')
    else
	let pattern	= matchstr(a:Arg, '^\zs\S*\ze')
	let flag	= matchstr(a:Arg, '^\S*\s*\zs['.a:flags.']*\ze\s*$')
    endif
    return [ pattern, flag ]
endfunction
"}}}
" {{{ Search()
try
function! atplib#search#Search(Bang, Arg)

    let atp_MainFile	= atplib#FullPath(b:atp_MainFile)
    let [ pattern, flag ] = atplib#search#GetSearchArgs(a:Arg, 'bceswWx')

    if pattern == ""
	echohl ErrorMsg
	echomsg "[ATP:] enclose the pattern with /.../"
	echohl None
	return
    endif

    let subfiles = atplib#search#SearchPackage('subfiles')

    if a:Bang == "!" || !exists("b:TreeOfFiles")
	call atplib#search#RecursiveSearch(atp_MainFile, expand("%:p"), 'make_tree', '', expand("%:p"), 1, 1, winsaveview(), bufnr("%"), reltime(), { 'no_options' : 'no_options' }, 'no_cwd', pattern, subfiles, flag)
    else
	call atplib#search#RecursiveSearch(atp_MainFile, expand("%:p"), '', deepcopy(b:TreeOfFiles),  expand("%:p"), 1, 1, winsaveview(), bufnr("%"), reltime(), { 'no_options' : 'no_options' }, 'no_cwd', pattern, subfiles, flag)
    endif

endfunction
catch /E127: Cannot redefine function/  
endtry
" }}}

function! atplib#search#ATP_ToggleNn(silent,...) " {{{
" With bang it is only used in RecursiveSearch function (where it is used
" twice in a row).
    let on	= ( a:0 ? ( a:1 == 'on' || string(a:1) == '1' ? 1 : 0 ) : !g:atp_mapNn )
    if !on
	silent! nunmap <buffer> n
	silent! nunmap <buffer> N
	silent! aunmenu LaTeX.Toggle\ Nn\ [on]
	let g:atp_mapNn	= 0
	nmenu 550.79 &LaTeX.Toggle\ &Nn\ [off]<Tab>:ToggleNn		:ToggleNn<CR>
	imenu 550.79 &LaTeX.Toggle\ &Nn\ [off]<Tab>:ToggleNn		<Esc>:ToggleNn<CR>a
	tmenu LaTeX.Toggle\ Nn\ [off] atp maps to n,N.
	if !a:silent
	    echomsg "[ATP:] vim nN maps"  
	endif
    else
	silent! nmap <buffer> <silent> n    <Plug>RecursiveSearchn
	silent! nmap <buffer> <silent> N    <Plug>RecursiveSearchN
	silent! aunmenu LaTeX.Toggle\ Nn\ [off]
	let g:atp_mapNn	= 1
	nmenu 550.79 &LaTeX.Toggle\ &Nn\ [on]<Tab>:ToggleNn			:ToggleNn<CR>
	imenu 550.79 &LaTeX.Toggle\ &Nn\ [on]<Tab>:ToggleNn			<Esc>:ToggleNn<CR>a
	tmenu LaTeX.Toggle\ Nn\ [on] n,N vim normal commands.
	if !a:silent
	    echomsg "[ATP:] atp nN maps"
	endif
    endif
endfunction
function! atplib#search#SearchHistCompletion(ArgLead, CmdLine, CursorPos)
    let search_history=[]
    let hist_entry	= histget("search")
    let nr = 0
    while hist_entry != ""
	call add(search_history, hist_entry)
	let nr 		-= 1
	let hist_entry	=  histget("search", nr)
    endwhile
    
    return filter(search_history, "v:val =~# '^'.a:ArgLead")
endfunction
"}}}
"}}}

" These are only variables and front end functions for Bib Search Engine of ATP.
" Search engine is define in autoload/atplib.vim script library.
"{{{ Bibliography Search
"-------------SEARCH IN BIBFILES ----------------------
" This function counts accurence of a:keyword in string a:line, 
" there are two methods keyword is a string to find (a:1=0)or a pattern to
" match, the pattern used to is a:keyword\zs.* to find the place where to cut.
" DEBUG:
" command -buffer -nargs=* Count :echo atplib#count(<args>)
" Front End Function
" {{{ BibSearch
"  There are three arguments: {pattern}, [flags, [choose]]
function! atplib#search#BibSearch(bang,...)
"     let pattern = a:0 >= 1 ? a:1 : ""
"     let flag	= a:0 >= 2 ? a:2 : ""
	
    let time=reltime()
	
    let Arg = ( a:0 >= 1 ? a:1 : "" )
    if Arg != ""
	let [ pattern, flag ] = atplib#search#GetSearchArgs(Arg, 'aetbjsynvpPNShouH@BcpmMtTulL')
    else
	let [ pattern, flag ] = [ "", ""] 
    endif

    let b:atp_LastBibPattern 	= pattern
    "     This cannot be set here.  It is set later by atplib#bibsearch#showresults function.
    "     let b:atp_LastBibFlags	= flag
    let @/			= pattern

    if g:atp_debugBS
	exe "redir! > ".g:atp_TempDir."/Bibsearch.log"
	silent! echo "==========BibSearch=========================="
	silent! echo "b:BibSearch_pattern=" . pattern
	silent! echo "b:BibSearch bang="    . a:bang
	silent! echo "b:BibSearch flag="    . flag	
	let g:BibSearch_pattern = pattern
	let g:BibSearch_bang	= a:bang
	let g:BibSearch_flag	= flag
	redir END
    endif

    if !exists("s:bibdict") || a:bang == "!"
	let s:bibdict={}
	if !exists("b:ListOfFiles") || !exists("b:TypeDict") || a:bang == "!"
	    call TreeOfFiles(b:atp_MainFile)
	endif
	for file in b:ListOfFiles
	    if b:TypeDict[file] == "bib"
		let s:bibdict[file]=readfile(file)
	    endif
	endfor
    endif
    let b:atp_BibFiles=keys(s:bibdict)
"     let g:bibdict=s:bibdict

    if has("python") && g:atp_bibsearch == "python"
	call atplib#bibsearch#showresults( atplib#bibsearch#searchbib_py(pattern, keys(s:bibdict), a:bang), flag, pattern, s:bibdict)
    else
	call atplib#bibsearch#showresults( atplib#bibsearch#searchbib(pattern, s:bibdict, a:bang), flag, pattern, s:bibdict)
    endif
    let g:time_BibSearch=reltimestr(reltime(time))
endfunction
" }}}
"}}}

" Other Searching Tools: 
" {{{1 atplib#search#KpsewhichGlobPath 
" 	a:format	is the format as reported by kpsewhich --help
" 	a:path		path if set to "", then kpsewhich will find the path.
" 			The default is what 'kpsewhich -show-path tex' returns
" 			with "**" appended. 
" 	a:name 		can be "*" then finds all files with the given extension
" 			or "*.cls" to find all files with a given extension.
" 	a:1		modifiers (the default is ":t:r")
" 	a:2		filters path names matching the pattern a:1
" 	a:3		filters out path names not matching the pattern a:2
"
" 	Argument a:path was added because it takes time for kpsewhich to return the
" 	path (usually ~0.5sec). ATP asks kpsewhich on start up
" 	(g:atp_kpsewhich_tex) and then locks the variable (this will work
" 	unless sb is reinstalling tex (with different personal settings,
" 	changing $LOCALTEXMF) during vim session - not that often). 
"
" Example: call atplib#search#KpsewhichGlobPath('tex', '', '*', ':p', '^\(\/home\|\.\)','\%(texlive\|kpsewhich\|generic\)')
" gives on my system only the path of current dir (/.) and my localtexmf. 
" this is done in 0.13s. The long pattern is to 
"
" atplib#search#KpsewhichGlobPath({format}, {path}, {expr=name}, [ {mods}, {pattern_1}, {pattern_2}]) 
function! atplib#search#KpsewhichGlobPath(format, path, name, ...)
    let time	= reltime()
    let modifiers = a:0 == 0 ? ":t:r" : a:1
    if a:path == ""
	let path	= substitute(substitute(system("kpsewhich -show-path ".a:format ),'!!','','g'),'\/\/\+','\/','g')
	let path	= substitute(path,':\|\n',',','g')
	let path_list	= split(path, ',')
	let idx		= index(path_list, '.')
	if idx != -1
	    let dot 	= remove(path_list, index(path_list,'.')) . ","
	else
	    let dot 	= ""
	endif
	call map(path_list, 'v:val . "**"')

	let path_list	= ['.']+path_list
	let path	= join(path_list, ',')
    else
	let path = a:path
    endif
    " If a:2 is non zero (if not given it is assumed to be 0 for compatibility
    " reasons)
    if get(a:000, 1, 0) != "0"
	if !exists("path_list")
	    let path_list	= split(path, ',')
	endif
	call filter(path_list, 'v:val =~ a:2')
	let path	= join(path_list, ',')
    endif
    if get(a:000, 2, 0) != "0"
	if !exists("path_list")
	    let path_list	= split(path, ',')
	endif
	call filter(path_list, 'v:val !~ a:3')
	let path	= join(path_list, ',')
    endif

    let list	= split(globpath(path, a:name),"\n") 
    if modifiers != ":p"
        call map(list, 'fnamemodify(v:val, modifiers)')
    endif
    let g:time_KpsewhichGlobPath=reltimestr(reltime(time))
    return list
endfunction
" }}}1
" {{{1 atplib#search#KpsewhichFindFile
" the arguments are similar to atplib#KpsewhichGlob except that the a:000 list
" is shifted:
" a:1		= path	
" 			if set to "" then kpsewhich will find the path.
" a:2		= count (as for findfile())
" 		  when count < 0 returns a list of all files found
" a:3		= modifiers 
" a:4		= positive filter for path (see KpsewhichGLob a:1)
" a:5		= negative filter for path (see KpsewhichFind a:2)
"
" needs +path_extra vim feature
"
" atp#KpsewhichFindFile({format}, {expr=name}, [{path}, {count}, {mods}, {pattern_1}, {pattern_2}]) 
function! atplib#search#KpsewhichFindFile(format, name, ...)

    " Unset the suffixadd option
    let saved_sua	= &l:suffixesadd
    let &l:sua	= ""

"     let time	= reltime()
    let path	= a:0 >= 1 ? a:1 : ""
    let l:count	= a:0 >= 2 ? a:2 : 0
    let modifiers = a:0 >= 3 ? a:3 : ""
    " This takes most of the time!
    if path == ""
	let path	= substitute(substitute(system("kpsewhich -show-path ".a:format ),'!!','','g'),'\/\/\+','\/','g')
	let path	= substitute(path,':\|\n',',','g')
	let path_list	= split(path, ',')
	let idx		= index(path_list, '.')
	if idx != -1
	    let dot 	= remove(path_list, index(path_list,'.')) . ","
	else
	    let dot 	= ""
	endif
	call map(path_list, 'v:val . "**"')

	let path	= dot . join(path_list, ',')
	unlet path_list
    endif


    " If a:2 is non zero (if not given it is assumed to be 0 for compatibility
    " reasons)
    if get(a:000, 3, 0) != 0
	let path_list	= split(path, ',')
	call filter(path_list, 'v:val =~ a:4')
	let path	= join(path_list, ',')
    endif
    if get(a:000, 4, 0) != 0
	let path_list	= split(path, ',')
	call filter(path_list, 'v:val !~ a:5')
	let path	= join(path_list, ',')
    endif

    if l:count >= 1
	let result	= findfile(a:name, path, l:count)
    elseif l:count == 0
	let result	= findfile(a:name, path)
    elseif l:count < 0
	let result	= findfile(a:name, path, -1)
    endif
	

    if l:count >= 0 && modifiers != ""
	let result	= fnamemodify(result, modifiers) 
    elseif l:count < 0 && modifiers != ""
	call map(result, 'fnamemodify(v:val, modifiers)')
    endif

    let &l:sua	= saved_sua
    return result
endfunction
" }}}1

" atplib#search#SearchPackage {{{1
"
" This function searches if the package in question is declared or not.
" Returns the line number of the declaration  or 0 if it was not found.
"
" It was inspired by autex function written by Carl Mueller, math at carlm e4ward c o m
" and made work for project files using lvimgrep.
"
" This function doesn't support plaintex files (\\input{})
" ATP support plaintex input lines in a different way (but not that flexible
" as this: for plaintex I use atplib#GrepPackageList on startup (only!) and
" then match input name with the list).
"
" name = package name (tikz library name)
" a:1  = stop line (number of the line \\begin{document} 
" a:2  = pattern matching the command (without '^[^%]*\\', just the name)
" to match \usetikzlibrary{...,..., - 
function! atplib#search#SearchPackage(name,...)

    let atp_MainFile	= atplib#FullPath(b:atp_MainFile)
    if !filereadable(atp_MainFile)
	silent echomsg "[ATP:] atp_MainFile : " . atp_MainFile . " is not readable "
	return
    endif
    let cwd = getcwd()
    if exists("b:atp_ProjectDir") && getcwd() != b:atp_ProjectDir
	exe "lcd " . fnameescape(b:atp_ProjectDir)
    endif

    if getbufvar("%", "atp_MainFile") == ""
	call SetProjectName()
    endif

    let com	= a:0 >= 2 ? a:2 : 'usepackage\s*\%(\[[^\]]*\]\)\?'

    " If the current file is the atp_MainFile
    if expand("%:p") == atp_MainFile

	if !exists("saved_pos")
	    let saved_pos=getpos(".")
	endif
	keepjumps call setpos(".",[0,1,1,0])
	let stop_line	= search('^\([^%]\|\\%]\)*\\begin\s*{\s*document\s*}', 'ncW')
	if stop_line != 0
	    keepjumps let ret = search('\C^[^%]*\\'.com.'\s*{[^}]*'.a:name,'ncW', stop_line)
	    keepjump call setpos(".",saved_pos)
	    exe "lcd " . fnameescape(cwd)
	    return ret
	else
	    keepjumps let ret = search('\C^[^%]*\\'.com.'\s*{[^}]*'.a:name,'ncW')
	    keepjump call setpos(".", saved_pos)
	    exe "lcd " . fnameescape(cwd)
	    return ret
	endif

    " If the current file is not the mainfile
    else
	" Cache the Preambule / it is not changing so this is completely safe /
	if !exists("s:Preambule")
	    let s:Preambule = readfile(atp_MainFile) 
	endif
	let lnum = 1
	for line in s:Preambule
	    if line =~ '^[^%]*\\'.com.'\s*{[^}]*\C'.a:name

		exe "lcd " . fnameescape(cwd)
		return lnum
	    endif
	    if line =~ '^\([^%]\|\\%\)*\\begin\s*{\s*document\s*}'
		if lnum < len(s:Preambule)
		    call remove(s:Preambule, lnum-1, -1)
		endif
		exe "lcd " . fnameescape(cwd)
		return 0
	    endif
	    let lnum += 1
	endfor
    endif

"     echo reltimestr(reltime(time))

    " If the package was not found return 0 
    exe "lcd " . fnameescape(cwd)
    return 0

endfunction
" }}}1
"{{{1 atplib#search#GrepPackageList
" This function returns list of packages declared in the b:atp_MainFile (or
" a:2). If the filetype is plaintex it returns list of all \input{} files in
" the b:atp_MainFile. 
" I'm not shure if this will be OK for project files written in plaintex: Can
" one declare a package in the middle of document? probably yes. So it might
" be better to use TreeOfFiles in that case.

" This takes =~ 0.02 s. This is too long to call it in complete#TabCompletion.
function! atplib#search#GrepPackageList(...)
" 	let time = reltime() 
    let file	= a:0 >= 2 ? a:2 : getbufvar("%", "atp_MainFile") 
    let pat	= a:0 >= 1 ? a:1 : ''
    if file == ""
	return []
    endif

    let ftype	= getbufvar(file, "&filetype")
    if pat == ''
	if ftype =~ '^\(ams\)\=tex$'
	    let pat	= '\\usepackage\s*\(\[[^]]*\]\)\=\s*{'
	elseif ftype == 'plaintex'
	    let pat = '\\input\s*{'
	else
    " 	echoerr "ATP doesn't recognize the filetype " . &l:filetype . ". Using empty list of packages."
	    return []
	endif
    endif

    let saved_loclist	= getloclist(0)
    try
	silent execute 'lvimgrep /^[^%]*'.pat.'/j ' . fnameescape(file)
    catch /E480:/
	call setloclist(0, [{'text' : 'empty' }])
    endtry
    let loclist		= getloclist(0)
    call setloclist(0, saved_loclist)

    let pre		= map(loclist, 'v:val["text"]')
    let pre_l		= []
    for line in pre
	let package_l	= matchstr(line, pat.'\zs[^}]*\ze}')
	call add(pre_l, package_l)
    endfor

    " We make a string of packages separeted by commas and the split it
    " (compatibility with \usepackage{package_1,package_2,...})
    let pre_string	= join(pre_l, ',')
    let pre_list	= split(pre_string, ',')
    call filter(pre_list, "v:val !~ '^\s*$'")

"      echo reltimestr(reltime(time))
    return pre_list
endfunction
"{{{1 atplib#search#GrepPreambule
function! atplib#search#GrepPreambule(pattern, ...)
    let saved_loclist 	= getloclist(0)
    let atp_MainFile	= ( a:0 >= 1 ? a:1 : b:atp_MainFile ) 
    let winview = winsaveview()
    exe 'silent! 1lvimgrep /^[^%]*\\begin\s*{\s*document\s*}/j ' . fnameescape(atp_MainFile)
    let linenr = get(get(getloclist(0), 0, {}), 'lnum', 'nomatch')
    if linenr == "nomatch"
	call setloclist(0, saved_loclist)
	return
    endif
    exe 'silent! lvimgrep /'.a:pattern.'\%<'.linenr.'l/jg ' . fnameescape(atp_MainFile) 
    let matches = getloclist(0)
    call setloclist(0, saved_loclist)
    return matches
endfunction

" atplib#search#DocumentClass {{{1
function! atplib#search#DocumentClass(file)

    let saved_loclist	= getloclist(0)
    " Note: lvimgrep command loads the buffer (as unlisted one),
    " but doesn't warn if there is a swap file (this is not the only place where
    " files are loaded on startup).
    try
	silent execute '1lvimgrep /^[^%]*\\documentclass/j ' . fnameescape(a:file)
    catch /E480:/
	return 0
    catch /E680:/
	return 0
    catch /E683:/
	return 0
    endtry
    let line		= get(get(getloclist(0), 0, { 'text' : "no_document_class"}), 'text')
    call setloclist(0, saved_loclist)


    if line != 'no_document_class'
	return substitute(l:line,'.*\\documentclass\s*\%(\[.*\]\)\?{\(.*\)}.*','\1','')
    endif
 
    return 0
endfunction
" }}}1

" Make a tree of input files.
" {{{ atplib#search#TreeOfFiles_vim
" this is needed to make backward searching.
" It returns:
" 	[ {tree}, {list}, {type_dict}, {level_dict} ]
" 	where {tree}:
" 		is a tree of files of the form
" 			{ file : [ subtree, linenr ] }
"		where the linenr is the linenr of \input{file} iline the one level up
"		file.
"	{list}:
"		is just list of all found input files (except the main file!).
"	{type_dict}: 
"		is a dictionary of types for files in {list}
"		type is one of: preambule, input, bib. 
"
" {flat} =  1 	do not be recursive
" {flat} =  0	the deflaut be recursive for input files (not bib and not preambule) 
" 		bib and preambule files are not added to the tree	
" {flat} = -1 	include input and premabule files into the tree
" 		

" TreeOfFiles({main_file}, [{pattern}, {flat}, {run_nr}])
" debug file - /tmp/tof_log
" a:main_file	is the main file to start with
function! atplib#search#TreeOfFiles_vim(main_file,...)
" let time	= reltime()

    let atp_MainFile = atplib#FullPath(b:atp_MainFile)

    if !exists("b:atp_OutDir")
	call atplib#common#SetOutDir(0, 1)
    endif

    let tree		= {}

    " flat = do a flat search, i.e. fo not search in input files at all.
    let flat		= a:0 >= 2	? a:2 : 0	

    " This prevents from long runs on package files
    " for example babel.sty has lots of input files.
    if expand("%:e") != 'tex'
	return [ {}, [], {}, {} ]
    endif
    let run_nr		= a:0 >= 3	? a:3 : 1 
    let biblatex	= 0

    " Adjust g:atp_inputfile_pattern if it is not set right 
    if run_nr == 1 
	let pattern = '^[^%]*\\\%(input\s*{\=\|include\s*{'
	if '\subfile{' !~ g:atp_inputfile_pattern && atplib#search#SearchPackage('subfiles')
	    let pattern .= '\|subfile\s*{'
	endif
	let biblatex = atplib#search#SearchPackage('biblatex')
	if biblatex
	    " If biblatex is present, search for bibliography files only in the
	    " preambule.
	    if '\addbibresource' =~ g:atp_inputfile_pattern || '\addglobalbib' =~ g:atp_inputfile_pattern || '\addsectionbib' =~ g:atp_inputfile_pattern || '\bibliography' =~ g:atp_inputfile_pattern
		echo "[ATP:] You might remove biblatex patterns from g:atp_inputfile_pattern if you use biblatex package."
	    endif
	    let biblatex_pattern = '^[^%]*\\\%(bibliography\s*{\|addbibresource\s*\%(\[[^]]*\]\)\?\s*{\|addglobalbib\s*\%(\[[^]]*\]\)\?\s*{\|addsectionbib\s*\%(\[[^]]*\]\)\?\s*{\)'
	else
	    let pattern .= '\|bibliography\s*{'
	endif
	let pattern .= '\)'
    endif
    let pattern		= a:0 >= 1 	? a:1 : g:atp_inputfile_pattern

	if g:atp_debugToF
	    if exists("g:atp_TempDir")
		if run_nr == 1
		    exe "redir! > ".g:atp_TempDir."/TreeOfFiles.log"
		else
		    exe "redir! >> ".g:atp_TempDir."/TreeOfFiles.log"
		endif
	    endif
	endif

	if g:atp_debugToF
	    silent echo run_nr . ") |".a:main_file."| expand=".expand("%:p") 
	endif
	
    if run_nr == 1
	let cwd		= getcwd()
	exe "lcd " . fnameescape(b:atp_ProjectDir)
    endif
	

    let line_nr		= 1
    let ifiles		= []
    let list		= []
    let type_dict	= {}
    let level_dict	= {}

    let saved_llist	= getloclist(0)
    if run_nr == 1 && &l:filetype =~ '^\(ams\)\=tex$'
	try
	    silent execute 'lvimgrep /\\begin\s*{\s*document\s*}/j ' . fnameescape(a:main_file)
	catch /E480:/
	endtry
	let end_preamb	= get(get(getloclist(0), 0, {}), 'lnum', 0)
	call setloclist(0,[])
	if biblatex
	    try
		silent execute 'lvimgrep /'.biblatex_pattern.'\%<'.end_preamb.'l/j ' . fnameescape(a:main_file)
	    catch /E480:/
	    endtry
	endif
    else
	let end_preamb	= 0
	call setloclist(0,[])
    endif

    try
	silent execute "lvimgrepadd /".pattern."/jg " . fnameescape(a:main_file)
    catch /E480:/
"     catch /E683:/ 
" 	let g:pattern = pattern
" 	let g:filename = fnameescape(a:main_file)
    endtry
    let loclist	= getloclist(0)
    call setloclist(0, saved_llist)
    let lines	= map(loclist, "[ v:val['text'], v:val['lnum'], v:val['col'] ]")

    	if g:atp_debugToF
	    silent echo run_nr . ") Lines: " .string(lines)
	endif

    for entry in lines

	    let [ line, lnum, cnum ] = entry
	    " input name (iname) as appeared in the source file
	    let iname	= substitute(matchstr(line, pattern . '\(''\|"\)\=\zs\f\%(\f\|\s\)*\ze\1\='), '\s*$', '', '') 
	    if iname == "" && biblatex 
		let iname	= substitute(matchstr(line, biblatex_pattern . '\(''\|"\)\=\zs\f\%(\f\|\s\)*\ze\1\='), '\s*$', '', '') 
	    endif
	    if g:atp_debugToF
		silent echo run_nr . ") iname=".iname
	    endif
	    if line =~ '{\s*' . iname
		let iname	= substitute(iname, '\\\@<!}\s*$', '', '')
	    endif

	    let iext	= fnamemodify(iname, ":e")
	    if g:atp_debugToF
		silent echo run_nr . ") iext=" . iext
	    endif

	    if iext == "ldf"  || 
			\( &filetype == "plaintex" && getbufvar(fnamemodify(b:atp_MainFile, ":t"), "&filetype") != "tex") 
			\ && expand("%:p") =~ 'texmf'
		" if the extension is ldf (babel.sty) or the file type is plaintex
		" and the filetype of main file is not tex (it can be empty when the
		" buffer is not loaded) then match the full path of the file: if
		" matches then doesn't go below this file. 
		if g:atp_debugToF
		    silent echo run_nr . ") CONTINUE"
		endif
		continue
	    endif

	    " type: preambule,bib,input.
	    if strpart(line, cnum-1)  =~ '^\s*\(\\bibliography\>\|\\addglobalbib\>\|\\addsectionbib\>\|\\addbibresource\>\)'
		let type	= "bib"
	    elseif lnum < end_preamb && run_nr == 1
		let type	= "preambule"
	    else
		let type	= "input"
	    endif

	    if g:atp_debugToF
		silent echo run_nr . ") type=" . type
	    endif

	    let inames	= []
	    if type != "bib"
		let inames		= [ atplib#append_ext(iname, '.tex') ]
	    else
		let inames		= map(split(iname, ','), "atplib#append_ext(v:val, '.bib')")
	    endif

	    if g:atp_debugToF
		silent echo run_nr . ") inames " . string(inames)
	    endif

	    " Find the full path only if it is not already given. 
	    for iname in inames
		let saved_iname = iname
		if iname != fnamemodify(iname, ":p")
		    if type != "bib"
			let iname	= atplib#search#KpsewhichFindFile('tex', iname, b:atp_OutDir . "," . g:atp_texinputs , 1, ':p', '^\%(\/home\|\.\)', '\(^\/usr\|texlive\|kpsewhich\|generic\|miktex\)')
		    else
			let iname	= atplib#search#KpsewhichFindFile('bib', iname, b:atp_OutDir . "," . g:atp_bibinputs , 1, ':p')
		    endif
		endif

		if fnamemodify(iname, ":t") == "" 
		    let iname  = expand(saved_iname, ":p")
		endif

		if g:atp_debugToF
		    silent echo run_nr . ") iname " . string(iname)
		endif

		if g:atp_RelativePath
		    let iname = atplib#RelativePath(iname, (fnamemodify(resolve(b:atp_MainFile), ":h")))
		endif

		call add(ifiles, [ iname, lnum] )
		call add(list, iname)
		call extend(type_dict, { iname : type } )
		call extend(level_dict, { iname : run_nr } )
	    endfor
    endfor

	    if g:atp_debugToF
		silent echo run_nr . ") list=".string(list)
	    endif

    " Be recursive if: flat is off, file is of input type.
    if !flat || flat <= -1
    for [ifile, line] in ifiles	
	if type_dict[ifile] == "input" && flat <= 0 || ( type_dict[ifile] == "preambule" && flat <= -1 )
	     let [ ntree, nlist, ntype_dict, nlevel_dict ] = atplib#search#TreeOfFiles_vim(ifile, pattern, flat, run_nr+1)

	     call extend(tree, 		{ ifile : [ ntree, line ] } )
	     call extend(list, nlist, index(list, ifile)+1)  
	     call extend(type_dict, 	ntype_dict)
	     call extend(level_dict, 	nlevel_dict)
	endif
    endfor
    else
	" Make the flat tree
	for [ ifile, line ]  in ifiles
	    call extend(tree, { ifile : [ {}, line ] })
	endfor
    endif

"	Showing time takes ~ 0.013sec.
"     if run_nr == 1
" 	echomsg "TIME:" . join(reltime(time), ".") . " main_file:" . a:main_file
"     endif
    let [ b:TreeOfFiles, b:ListOfFiles, b:TypeDict, b:LevelDict ] = deepcopy([ tree, list, type_dict, level_dict])

    " restore current working directory
    if run_nr == 1
	exe "lcd " . fnameescape(cwd)
    endif

    if g:atp_debugToF && run_nr == 1
	silent! echo "========TreeOfFiles========================"
	silent! echo "TreeOfFiles b:ListOfFiles=" . string(b:ListOfFiles)
	redir END
    endif


    return [ tree, list, type_dict, level_dict ]

endfunction "}}}
" atplib#search#TreeOfFiles_py "{{{
function! atplib#search#TreeOfFiles_py(main_file)
let time=reltime()
python << END_PYTHON
import vim, re, subprocess, os, glob

filename=vim.eval('a:main_file')
relative_path=vim.eval('g:atp_RelativePath')
project_dir=vim.eval('b:atp_ProjectDir')

def vim_remote_expr(servername, expr):
# Send <expr> to vim server,

# expr must be well quoted:
#       vim_remote_expr('GVIM', "atplib#callback#TexReturnCode()")
    cmd=[options.progname, '--servername', servername, '--remote-expr', expr]
    subprocess.Popen(cmd, stdout=subprocess.PIPE).wait()

def isnonempty(string):
    if str(string) == "":
        return False
    else:
        return True

def scan_preambule(file, pattern):
# scan_preambule for a pattern

# file is list of lines
    for line in file:
        ret=re.search(pattern, line)
        if ret:
            return True
        elif re.search('\\\\begin\s*{\s*document\s*}', line):
            return False
    return False

def preambule_end(file):
# find linenr where preambule ends,

# file is list of lines
    nr=1
    for line in file:
        if re.search('\\\\begin\s*{\s*document\s*}', line):
            return nr
        nr+=1
    return 0

def addext(string, ext):
# the pattern is not matching .tex extension read from file.
    if not re.search("\."+ext+"$", string):
        return string+"."+ext
    else:
        return string

def kpsewhich_path(format):
# find fname of format in path given by kpsewhich,

    kpsewhich=subprocess.Popen(['kpsewhich', '-show-path', format], stdout=subprocess.PIPE)
    kpsewhich.wait()
    path=kpsewhich.stdout.read()
    path=re.sub("!!", "",path)
    path=re.sub("\/\/+", "/", path)
    path=re.sub("\n", "",path)
    path_list=path.split(":")
    return path_list

def kpsewhich_find(file, path_list):
    results=[]
    for path in path_list:
        found=glob.glob(os.path.join(path, file))
        results.extend(found)
        found=glob.glob(os.path.join(path, file))
        results.extend(found)
    return results

def bufnumber(file):
    cdir = os.path.abspath(os.curdir)
    os.chdir(project_dir)
    for buffer in vim.buffers:
        # This requires that we are in the directory of the main tex file:
        try:
            if buffer.name == os.path.abspath(file):
                os.chdir(cdir)
                return buffer.number
        except:
            pass
    for buffer in vim.buffers:
        try:
            if os.path.basename(buffer.name) == file:
                os.chdir(cdir)
                return buffer.number
        except:
            pass
    os.chdir(cdir)
    return 0

def scan_file(file, fname, pattern, bibpattern):
# scan file for a pattern, return all groups,

# file is a list of lines, 
    matches_d={}
    matches_l=[]
    nr = 0
    for line in file:
        nr+=1
        match_all=re.findall(pattern, line)
        if len(match_all) > 0:
            for match in match_all:
                for m in match:
                    if str(m) != "":
                        m=addext(m, "tex")
                        if not os.access(m, os.F_OK):
                            try:
                                m=kpsewhich_find(m, tex_path)[0]
                            except IndexError:
                                pass
                        elif relative_path == "0":
                            m=os.path.join(project_dir,m)
                        if fname == filename and nr < preambule_end:
                            matches_d[m]=[m, fname, nr, 'preambule']
                            matches_l.append(m)
                        else:
                            matches_d[m]=[m, fname, nr, 'input']
                            matches_l.append(m)
        match_all=re.findall(bibpattern, line)
        if len(match_all) > 0:
            for match in match_all:
                if str(match) != "":
                    for m in  match.split(','):
                        m=addext(m, "bib")
                        if not os.access(m, os.F_OK):
                            m=kpsewhich_find(m, bib_path)[0]
                        matches_d[m]=[m, fname,  nr, 'bib']
                        matches_l.append(m)
    return [ matches_d, matches_l ]

def tree(file, level, pattern, bibpattern):
# files - list of file names to scan, 

    bufnr = bufnumber(file)
    if bufnr in vim.buffers:
        file_l = vim.buffers[bufnr]
    else:
        try:
            file_ob = open(file, 'r')
        except IOError:
            if re.search('\.bib$', file):
                path=bib_path
            else:
                path=tex_path
            try:
                file=kpsewhich_find(file, path)[0]
            except IndexError:
                pass
            try:
                file_ob = open(file, 'r')
            except IOError:
                return [ {}, [], {}, {} ]
        file_l  = file_ob.read().split("\n")
        file_ob.close()
    [found, found_l] =scan_file(file_l, file, pattern, bibpattern)
    t_list=[]
    t_level={}
    t_type={}
    t_tree={}
    for item in found_l:
        t_list.append(item)
        t_level[item]=level
        t_type[item]=found[item][3]
    i_list=[]
    for file in t_list:
        if found[file][3]=="input":
            i_list.append(file)
    for file in i_list:
        [ n_tree, n_list, n_type, n_level ] = tree(file, level+1, pattern, bibpattern)
        for f in n_list:
            t_list.append(f)
            t_type[f]   =n_type[f]
            t_level[f]  =n_level[f]
        t_tree[file]    = [ n_tree, found[file][2] ]
    return [ t_tree, t_list, t_type, t_level ]

try:
    mainfile_ob = open(filename, 'r')
    mainfile    = mainfile_ob.read().split("\n")
    mainfile_ob.close()
    if scan_preambule(mainfile, re.compile('\\\\usepackage\s*{\s*subfiles\s*}')):
	pat_str='^[^%]*(?:\\\\input\s+([\w_\-\.]*)|\\\\(?:input|include(?:only)?|subfile)\s*{([^}]*)})'
	pattern=re.compile(pat_str)
    else:
	pat_str='^[^%]*(?:\\\\input\s+([\w_\-\.]*)|\\\\(?:input|include(?:only)?)\s*{([^}]*)})'
	pattern=re.compile(pat_str)

    bibpattern=re.compile('^[^%]*\\\\(?:bibliography|addbibresource|addsectionbib(?:\s*\[.*\])?|addglobalbib(?:\s*\[.*\])?)\s*{([^}]*)}')

    bib_path=kpsewhich_path('bib')
    tex_path=kpsewhich_path('tex')
    preambule_end=preambule_end(mainfile)

# Make TreeOfFiles:
    [ tree_of_files, list_of_files, type_dict, level_dict]= tree(filename, 1, pattern, bibpattern)
    vim.command("let b:TreeOfFiles="+str(tree_of_files))
    vim.command("let b:ListOfFiles="+str(list_of_files))
    vim.command("let b:TypeDict="+str(type_dict))
    vim.command("let b:LevelDict="+str(level_dict))
except IOError:
    vim.command("let b:TreeOfFiles={}")
    vim.command("let b:ListOfFiles=[]")
    vim.command("let b:TypeDict={}")
    vim.command("let b:LevelDict={}")
END_PYTHON
let g:time_TreeOfFiles_py=reltimestr(reltime(time))
endfunction
"}}}

" This function finds all the input and bibliography files declared in the source files (recursive).
" {{{ atplib#search#FindInputFiles 
" Returns a dictionary:
" { <input_name> : [ 'bib', 'main file', 'full path' ] }
"			 with the same format as the output of FindInputFiles
" a:MainFile	- main file (b:atp_MainFile)
" a:1 = 0 [1]	- use cached values of tree of files.
function! atplib#search#FindInputFiles(MainFile,...)

"     let time=reltime()
    call atplib#write("nobackup")

    let cached_Tree	= a:0 >= 1 ? a:1 : 0

    let saved_llist	= getloclist(0)
    call setloclist(0, [])

    if cached_Tree && exists("b:TreeOfFiles")
	let [ TreeOfFiles, ListOfFiles, DictOfFiles, LevelDict ]= deepcopy([ b:TreeOfFiles, b:ListOfFiles, b:TypeDict, b:LevelDict ]) 
    else
	
	if &filetype == "plaintex"
	    let flat = 1
	else
	    let flat = 0
	endif

	let [ TreeOfFiles, ListOfFiles, DictOfFiles, LevelDict ]= TreeOfFiles(fnamemodify(a:MainFile, ":p"), g:atp_inputfile_pattern, flat)
	" Update the cached values:
	let [ b:TreeOfFiles, b:ListOfFiles, b:TypeDict, b:LevelDict ] = deepcopy([ TreeOfFiles, ListOfFiles, DictOfFiles, LevelDict ])
    endif

    let AllInputFiles	= keys(filter(copy(DictOfFiles), " v:val == 'input' || v:val == 'preambule' "))
    let AllBibFiles	= keys(filter(copy(DictOfFiles), " v:val == 'bib' "))

    let b:AllInputFiles	= deepcopy(AllInputFiles)
    let b:AllBibFiles	= deepcopy(AllBibFiles)
    let b:atp_BibFiles	= copy(b:AllBibFiles)


    " this variable will store unreadable bibfiles:    
    let NotReadableInputFiles=[]

    " this variable will store the final result:   
    let Files		= {}

    for File in ListOfFiles
	let File_Path	= atplib#FullPath(File)
	if filereadable(File) 
	call extend(Files, 
	    \ { fnamemodify(File_Path,":t:r") : [ DictOfFiles[File] , fnamemodify(a:MainFile, ":p"), File_Path ] })
	else
	" echo warning if a bibfile is not readable
" 	    echohl WarningMsg | echomsg "File " . File . " not found." | echohl None
	    if count(NotReadableInputFiles, File_Path) == 0 
		call add(NotReadableInputFiles, File_Path)
	    endif
	endif
    endfor
    let g:NotReadableInputFiles	= NotReadableInputFiles

    " return the list  of readable bibfiles
"     let g:time_FindInputFiles=reltimestr(reltime(time))
    return Files
endfunction
function! atplib#search#UpdateMainFile()
    if b:atp_MainFile =~ '^\s*\/'
	let cwd = getcwd()
	exe "lcd " . fnameescape(b:atp_ProjectDir)
	let b:atp_MainFile	= ( g:atp_RelativePath ? fnamemodify(b:atp_MainFile, ":.") : b:atp_MainFile )
	exe "lcd " . fnameescape(cwd)
    else
	let b:atp_MainFile	= ( g:atp_RelativePath ? b:atp_MainFile : atplib#FullPath(b:atp_MainFile) )
    endif
    return
endfunction
"}}}
" vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1
autoload/atplib/tools.vim	[[[1
571
" Title: 	Vim library for ATP filetype plugin.
" Author:	Marcin Szamotulski
" Email:	mszamot [AT] gmail [DOT] com
" Note:		This file is a part of Automatic Tex Plugin for Vim.
" URL:		https://launchpad.net/automatictexplugin
" Language:	tex

" Open Function:
 "{{{1 atplib#tools#Open
 " a:1	- pattern or a file name
 " 		a:1 is regarded as a filename if filereadable(pattern) is non
 " 		zero.
function! atplib#tools#Open(bang, dir, TypeDict, ...)
    if a:dir == "0"
	echohl WarningMsg 
	echomsg "You have to set g:atp_LibraryPath in your vimrc or atprc file." 
	echohl None
	return
    endif

    let pattern = ( a:0 >= 1 ? a:1 : "") 
    let file	= filereadable(pattern) ? pattern : ""

    if file == ""
	if a:bang == "!" || !exists("g:atp_Library")
	    let g:atp_Library 	= filter(split(globpath(a:dir, "*"), "\n"), 'count(keys(a:TypeDict), fnamemodify(v:val, ":e"))')
	    let found 		= deepcopy(g:atp_Library) 
	else
	    let found		= deepcopy(g:atp_Library)
	endif
	call filter(found, "fnamemodify(v:val, ':t') =~ pattern")
	" Resolve symlinks:
	call map(found, "resolve(v:val)")
	" Remove double entries:
	call filter(found, "count(found, v:val) == 1")
	if len(found) > 1
	    echohl Title 
	    echo "Found files:"
	    echohl None
	    let i = 1
	    for file in found
		if len(map(copy(found), "v:val =~ escape(fnamemodify(file, ':t'), '~') . '$'")) == 1
		    echo i . ") " . fnamemodify(file, ":t")
		else
		    echo i . ") " . pathshorten(fnamemodify(file, ":p"))
		endif
		let i+=1
	    endfor
	    let choice = input("Which file to open? ")-1
	    if choice == -1
		return
	    endif
	    let file = found[choice]
	elseif len(found) == 1
	    let file = found[0]
	else
	    echohl WarningMsg
	    echomsg "[ATP:] Nothing found."
	    echohl None
	    return
	endif
    endif

    let ext 	= fnamemodify(file, ":e")
    let viewer 	= get(a:TypeDict, ext, 0) 

    if viewer == '0'
	echomsg "\n"
	echomsg "[ATP:] filetype: " . ext . " is not supported, add an entry to g:atp_OpenTypeDict" 
	return
    endif
    if viewer !~ '^\s*cat\s*$' && viewer !~ '^\s*g\=vim\s*$' && viewer !~ '^\s*edit\s*$' && viewer !~ '^\s*tabe\s*$' && viewer !~ '^\s*split\s*$'
	call system(viewer . " '" . file . "' &")  
    elseif viewer =~ '^\s*g\=vim\s*$' || viewer =~ '^\s*tabe\s*$'
	exe "tabe " . fnameescape(file)
	setl nospell
    elseif viewer =~ '^\s*edit\s*$' || viewer =~ '^\s*split\s*$'
	exe viewer . " " . fnameescape(file)
	setl nospell
    elseif viewer == '^\s*cat\s*'
	redraw!
	echohl Title
	echo "cat '" . file . "'"
	echohl None
	echo system(viewer . " '" . file . "' &")  
    endif
endfunction
"}}}1

" Labels Tools: GrepAuxFile, SrotLabels, generatelabels and showlabes.
" {{{1 LABELS
" the argument should be: resolved full path to the file:
" resove(fnamemodify(bufname("%"),":p"))

" {{{2 --------------- atplib#tools#GrepAuxFile
" This function searches in aux file (actually it tries first ._aux file,
" made by compile.py - this is because compile.py is copying aux file only if
" there are no errors (to not affect :Labels command)
function! atplib#tools#GrepAuxFile(...)
    " Aux file to read:

    let base = ( a:0 >= 1 ? fnamemodify(a:1, ":r") : fnamemodify(b:atp_MainFile, ":r") ) 
    let aux_filename	= base."._aux"
    if !filereadable(aux_filename)
	let aux_filename	= a:1
	if !filereadable(a:1) && exists("b:atp_MainFile")
	    let aux_filename = fnamemodify(atplib#FullPath(b:atp_MainFile), ":r") . "._aux"
	    if !filereadable(aux_filename)
		let aux_filename = fnamemodify(atplib#FullPath(b:atp_MainFile), ":r") . ".aux"
	    else
		echoerr "[ATP] aux file not found (atplib#tools#GrepAuxFile)."
	    endif
	endif
    endif

    let tex_filename	= fnamemodify(aux_filename, ":r") . ".tex"

    if !filereadable(aux_filename)
	" We should worn the user that there is no aux file
	" /this is not visible ! only after using the command 'mes'/
	echohl WarningMsg
        if exists("b:atp_TexCompiler")
            echomsg "[ATP:] there is no aux file. Run ".b:atp_TexCompiler." first."
        else
            echomsg "[ATP:] there is no aux file. "
        endif
	echohl None
	return []
	" CALL BACK is not working
	" I can not get output of: vim --servername v:servername --remote-expr v:servername
	" for v:servername
	" Here we should run latex to produce auxfile
" 	echomsg "Running " . b:atp_TexCompiler . " to get aux file."
" 	let labels 	= system(b:atp_TexCompiler . " -interaction nonstopmode " . atp_MainFile . " 1&>/dev/null  2>1 ; " . " vim --servername ".v:servername." --remote-expr 'atplib#tools#GrepAuxFile()'")
" 	return labels
    endif
"     let aux_file	= readfile(aux_filename)

    let saved_llist	= getloclist(0)
    if bufloaded(aux_filename)
	exe "silent! bd! " . bufnr(aux_filename)
    endif
    try
	silent execute 'lvimgrep /\\newlabel\s*{/j ' . fnameescape(aux_filename)
    catch /E480:/
    endtry
    let loc_list	= getloclist(0)
    call setloclist(0, saved_llist)
    call map(loc_list, ' v:val["text"]')

    let labels		= []
    if g:atp_debugGAF
	let g:gaf_debug	= {}
    endif

    " Equation counter depedns on the option \numberwithin{equation}{section}
    " /now this only supports article class.
    let equation = len(atplib#search#GrepPreambule('^\s*\\numberwithin{\s*equation\s*}{\s*section\s*}', tex_filename))
"     for line in aux_file
    for line in loc_list
    if line =~ '\\newlabel\>'
	let line = substitute(line, '\\GenericError\s*\%({[^}]*}\)\{4}', '', 'g')
	" line is of the form:
	" \newlabel{<label>}{<rest>}
	" where <rest> = {<label_number}{<title>}{<counter_name>.<counter_number>}
	" <counter_number> is usually equal to <label_number>.
	"
	" Document classes: article, book, amsart, amsbook, review:
	" NEW DISCOVERY {\zs\%({[^}]*}\|[^}]\)*\ze} matches for inner part of 
	" 	{ ... { ... } ... }	/ only one level of being recursive / 
	" 	The order inside the main \%( \| \) is important.
	"This is in the case that the author put in the title a command,
	"for example \mbox{...}, but not something more difficult :)
	if line =~ '^\\newlabel{[^}]*}{{[^}]*}{[^}]*}{\%({[^}]*}\|[^}]\)*}{[^}]*}'
	    let label	= matchstr(line, '^\\newlabel\s*{\zs[^}]*\ze}')
	    let rest	= matchstr(line, '^\\newlabel\s*{[^}]*}\s*{\s*{\zs.*\ze}\s*$')
	    let l:count = 1
	    let i	= 0
	    while l:count != 0 
		let l:count = ( rest[i] == '{' ? l:count+1 : rest[i] == '}' ? l:count-1 : l:count )
		let i+= 1
	    endwhile
	    let number	= substitute(strpart(rest,0,i-1), '{\|}', '', 'g')  
	    let rest	= strpart(rest,i)
	    let rest	= substitute(rest, '^{[^}]*}{', '', '')
	    let l:count = 1
	    let i	= 0
	    while l:count != 0 
		let l:count = rest[i] == '{' ? l:count+1 : rest[i] == '}' ? l:count-1 : l:count 
		let i+= 1
	    endwhile
	    let counter	= substitute(strpart(rest,i-1), '{\|}', '', 'g')  
	    let counter	= strpart(counter, 0, stridx(counter, '.')) 

	" Document classes: article, book, amsart, amsbook, review
	" (sometimes the format is a little bit different)
	elseif line =~ '\\newlabel{[^}]*}{{\d\%(\d\|\.\)*{\d\%(\d\|\.\)*}}{\d*}{\%({[^}]*}\|[^}]\)*}{[^}]*}'
	    let list = matchlist(line, 
		\ '\\newlabel{\([^}]*\)}{{\(\d\%(\d\|\.\)*{\d\%(\d\|\.\)*\)}}{\d*}{\%({[^}]*}\|[^}]\)*}{\([^}]*\)}')
	    let [ label, number, counter ] = [ list[1], list[2], list[3] ]
	    let number	= substitute(number, '{\|}', '', 'g')
	    let counter	= matchstr(counter, '^\w\+')

	" Document class: article
	elseif line =~ '\\newlabel{[^}]*}{{\d\%(\d\|\.\)*}{\d\+}}'
	    let list = matchlist(line, '\\newlabel{\([^}]*\)}{{\(\d\%(\d\|\.\)*\)}{\d\+}}')
	    let [ label, number, counter ] = [ list[1], list[2], "" ]

	" Memoir document class uses '\M@TitleReference' command
	" which doesn't specify the counter number.
	elseif line =~ '\\M@TitleReference' 
	    let label	= matchstr(line, '^\\newlabel\s*{\zs[^}]*\ze}')
	    let number	= matchstr(line, '\\M@TitleReference\s*{\zs[^}]*\ze}') 
	    let number	= substitute(number, '\\\%(text\|math\)\?\%(rm\|sf\|it\|bf\)\>\s*', '', 'g')
	    let number  = substitute(number, '(\|)', '', 'g')
	    let counter	= matchstr(line, '{\zs[^}]*\ze}{[^}]*}}$')

	elseif line =~ '\\newlabel{[^}]*}{.*\\relax\s}{[^}]*}{[^}]*}}'
	    " THIS METHOD MIGHT NOT WORK WELL WITH: book document class.
	    let label 	= matchstr(line, '\\newlabel{\zs[^}]*\ze}{.*\\relax\s}{[^}]*}{[^}]*}}')
	    let nc 		= matchstr(line, '\\newlabel{[^}]*}{.*\\relax\s}{\zs[^}]*\ze}{[^}]*}}')
	    let counter	= matchstr(nc, '\zs\a*\ze\(\.\d\+\)\+')
	    let number	= matchstr(nc, '.*\a\.\zs\d\+\(\.\d\+\)\+') 
	    if counter == 'equation' && !equation
		let number = matchstr(number, '\d\+\.\zs.*')
	    endif

	" aamas2010 class
	elseif line =~ '\\newlabel{[^}]*}{{\d\%(\d\|.\)*{\d\%(\d\|.\)*}{[^}]*}}' && atplib#search#DocumentClass(b:atp_MainFile) =~? 'aamas20\d\d'
	    let label 	= matchstr(line, '\\newlabel{\zs[^}]*\ze}{{\d\%(\d\|.\)*{\d\%(\d\|.\)*}{[^}]*}}')
	    let number 	= matchstr(line, '\\newlabel{\zs[^}]*\ze}{{\zs\d\%(\d\|.\)*{\d\%(\d\|.\)*\ze}{[^}]*}}')
	    let number	= substitute(number, '{\|}', '', 'g')
	    let counter	= ""

	" subeqautions
	elseif line =~ '\\newlabel{[^}]*}{{[^}]*}{[^}]*}}'
	    let list 	= matchlist(line, '\\newlabel{\([^}]*\)}{{\([^}]*\)}{\([^}]*\)}}')
	    let [ label, number ] = [ list[1], list[2] ]
	    let counter	= ""

	" AMSBook uses \newlabel for tocindent
	" which we filter out here.
	elseif line =~ '\\newlabel{[^}]*}{{\d\+.\?{\?\d*}\?}{\d\+}}'
	    let list 	= matchlist(line,  '\\newlabel{\([^}]*\)}{{\(\d\+.\?{\?\d*}\?\)}{\(\d\+}\)}')
	    let [ label, number ] = [ list[1], list[2] ]
	    let number 	= substitute(number, '\%({\|}\)', '', 'g')
	    let counter 	= ""
	else
	    let label	= "nolabel: " . line
	endif

	if label !~ '^nolabel:\>'
	    let number = substitute(number, '{\|}', '', 'g')
	    call add(labels, [ label, number, counter])
	    if g:atp_debugGAF
		call extend(g:gaf_debug, { label : [ number, counter ] })
	    endif
	endif
    endif
    endfor

    return labels
endfunction
" }}}2
" Sorting function used to sort labels.
" {{{2 --------------- atplib#tools#SortLabels
" It compares the first component of lists (which is line number)
" This should also use the bufnr.
function! atplib#tools#SortLabels(list1, list2)
    if a:list1[0] == a:list2[0]
	return 0
    elseif str2nr(a:list1[0]) > str2nr(a:list2[0])
	return 1
    else
	return -1
    endif
endfunction
" }}}2
" Function which find all labels and related info (label number, lable line
" number, {bufnr} <= TODO )
" {{{2 --------------- atplib#tools#generatelabels
" This function runs in two steps:
" 	(1) read lables from aux files using GrepAuxFile()
" 	(2) search all input files (TreeOfFiles()) for labels to get the line
" 		number 
" 	   [ this is done using :vimgrep which is fast, when the buffer is not loaded ]
function! atplib#tools#generatelabels(filename, ...)

    let time=reltime()
    let s:labels	= {}
    let bufname		= fnamemodify(a:filename, ':t')
    let auxname		= fnamemodify(a:filename, ':r') . ".aux"
    let return_ListOfFiles	= a:0 >= 1 ? a:1 : 1

    let true=1
    let i=0

    let aux_labels	= atplib#tools#GrepAuxFile(auxname)

    let saved_pos	= getpos(".")
    call cursor(1,1)

    let [ TreeOfFiles, ListOfFiles, TypeDict, LevelDict ] = TreeOfFiles(a:filename)
    let ListOfFiles_orig = copy(ListOfFiles)
    if count(ListOfFiles, a:filename) == 0
	call add(ListOfFiles, a:filename)
	let TypeDict[a:filename] = "input"
    endif
    let saved_llist	= getloclist(0)
    call setloclist(0, [])

    let InputFileList = filter(copy(ListOfFiles), "get(TypeDict, v:val, '') == 'input'")
    call map(InputFileList, "atplib#FullPath(v:val)")

    " Look for labels in all input files.
    if !has("python")
	for file in InputFileList
	    silent! execute "keepjumps lvimgrepadd /\\label\s*{/j " . fnameescape(file)
	endfor
	let loc_list	= getloclist(0)
	call setloclist(0, saved_llist)
	call map(loc_list, '[ v:val["lnum"], v:val["text"], fnamemodify(bufname(v:val["bufnr"]), ":p") ]')
    else
" We should save all files before.
" Using this python grep makes twice as fast.
python << EOF
import vim, re
files = vim.eval("InputFileList")
loc_list = []
for file in files:
    file_o = open(file, 'r')
    file_l = file_o.readlines()
    file_o.close()
    lnr = 0
    for line in file_l:
        lnr += 1
	matches = re.findall('^(?:[^%]*|\\\\%)\\\\label\s*{\s*([^}]*)\s*}', line)
	for m in matches:
            loc_list.append([ lnr, m, file])
vim.command("let loc_list="+str(loc_list))
EOF
	endif

    let labels = {}

    for label in aux_labels
        if !has("python")
            let dict		= filter(copy(loc_list), "v:val[1] =~ '\\label\s*{\s*'.escape(label[0], '*\/$.') .'\s*}'")
        else
            let dict		= filter(copy(loc_list), "v:val[1] ==# label[0]")
        endif
	let line		= get(get(dict, 0, []), 0, "") 
	let bufname		= get(get(dict, 0, []), 2, "")
	let bufnr		= bufnr(bufname)
	if line != ''
	    " Add only labels which have a line number (i.e. the ones that are
	    " present in the tex file: when ones deletes a label it will
	    " disappear from aux file only after compilation).
	    if get(labels, bufname, []) == []
		let labels[bufname] = [ [line, label[0], label[1], label[2], bufnr ] ]
	    else
		call add(labels[bufname], [line, label[0], label[1], label[2], bufnr ]) 
	    endif
	endif
    endfor

    for bufname in keys(labels)
	call sort(labels[bufname], "atplib#tools#SortLabels")
    endfor

    if exists("t:atp_labels")
	call extend(t:atp_labels, labels, "force")
    else
	let t:atp_labels	= labels
    endif
    keepjumps call setpos(".", saved_pos)
    let g:time_generatelabels=reltimestr(reltime(time))
    if return_ListOfFiles
	return [ t:atp_labels, ListOfFiles_orig ]
    else
	return t:atp_labels
    endif
endfunction
" }}}2
" This function opens a new window and puts the results there.
" {{{2 --------------- atplib#tools#showlabels
" the argument is [ t:atp_labels, ListOfFiles ] 
" 	where ListOfFiles is the list returne by TreeOfFiles() 
function! atplib#tools#showlabels(labels)

    " the argument a:labels=t:atp_labels[bufname("")] !
    let l:cline=line(".")

    let saved_pos	= getpos(".")

    " Open new window or jump to the existing one.
    let l:bufname	= bufname("")
    let l:bufpath	= fnamemodify(resolve(fnamemodify(bufname("%"),":p")),":h")
    let BufFullName	= fnamemodify(l:bufname, ":p") 

    let l:bname="__Labels__"

    let t:atp_labelswinnr=winnr()
    let t:atp_labelsbufnr=bufnr("^".l:bname."$")
    let l:labelswinnr=bufwinnr(t:atp_labelsbufnr)

    let tabstop	= 0
    for file in a:labels[1]
	let dict	= get(a:labels[0], file, [])
	let tabstop	= max([tabstop, max(map(copy(dict), "len(v:val[2])")) + 1])
	unlet dict
    endfor
"     let g:labelswinnr	= l:labelswinnr
    let saved_view	= winsaveview()

    if l:labelswinnr != -1
	" Jump to the existing window.
	redraw
	exe l:labelswinnr . " wincmd w"
	if l:labelswinnr != t:atp_labelswinnr
	    setl modifiable
	    silent exe "%delete"
	else
	    echoerr "ATP error in function s:showtoc, TOC/LABEL "
			\. "buffer and the tex file buffer agree."
	    return
	endif
    else

    " Open new window if its width is defined (if it is not the code below
    " will put lab:cels in the current buffer so it is better to return.
	if !exists("t:atp_labels_window_width")
	    echoerr "t:atp_labels_window_width not set"
	    return
	endif

	" tabstop option is set to be the longest counter number + 1
	redraw
	let toc_winnr=bufwinnr(bufnr("__ToC__"))
	if toc_winnr != -1
	    exe toc_winnr."wincmd w"
	    let split_cmd = "below split"
	else
	    let split_cmd = "vsplit"
	endif
	let labels_winnr=bufwinnr(bufnr("__Labels__"))
	if labels_winnr == -1
	    let openbuffer= "keepalt " . (toc_winnr == -1 ? t:atp_labels_window_width : ''). split_cmd." +setl\\ tabstop=" . tabstop . "\\ buftype=nofile\\ modifiable\\ noswapfile\\ bufhidden=delete\\ nobuflisted\\ filetype=toc_atp\\ syntax=labels_atp\\ nowrap\\ nonumber\\ norelativenumber\\ winfixwidth\\ nospell __Labels__"
	    silent exe openbuffer
	else
	    exe labels_winnr."wincmd w"
	    setl modifiable
	endif
	let t:atp_labelsbufnr=bufnr("")
    endif
    unlockvar b:atp_Labels
    let b:atp_Labels	= {}

    let line_nr	= 2
    for file in a:labels[1]
	if !(len(get(a:labels[0], file, []))>0)
	    continue
	endif
	call setline("$", fnamemodify(file, ":t") . " (" . fnamemodify(file, ":h")  . ")")
	call extend(b:atp_Labels, { 1 : [ file, 0 ]})
	for label in get(a:labels[0], file, [])
	    " Set line in the format:
	    " /<label_numberr> \t[<counter>] <label_name> (<label_line_nr>)/
	    " if the <counter> was given in aux file (see the 'counter' variable in atplib#tools#GrepAuxFile())
	    " print it.
	    " /it is more complecated because I want to make it as tight as
	    " possible and as nice as possible :)
	    " the first if checks if there are counters, then counter type is
	    " printed, then the tabs are set./
    " 	let slen	= winwidth(0)-tabstop-5-5
    " 	let space_len 	= max([1, slen-len(label[1])])
	    if tabstop+(len(label[3][0])+3)+len(label[1])+(len(label[0])+2) < winwidth(0)
		let space_len	= winwidth(0)-(tabstop+(len(label[3][0])+3)+len(label[1])+(len(label[0])+2))
	    else
		let space_len  	= 1
	    endif
	    let space	= join(map(range(space_len), '" "'), "")
	    let set_line 	= label[2] . "\t[" . label[3][0] . "] " . label[1] . space . "(" . label[0] . ")"
	    call setline(line_nr, set_line ) 
	    call extend(b:atp_Labels, { line_nr : [ file, label[0] ]}) 
	    let line_nr+=1
	endfor
    endfor
    lockvar 3 b:atp_Labels

    " set the cursor position on the correct line number.
    call search(l:bufname, 'w')
    let l:number=1
    for label  in get(a:labels[0], BufFullName, [])
	if l:cline >= label[0]
	    keepjumps call cursor(line(".")+1, col("."))
	elseif l:number == 1 && l:cline < label[0]
	    keepjumps call cursor(line(".")+1, col("."))
	endif
	let l:number+=1
    endfor
    setlocal nomodifiable
endfunction
" }}}2
" }}}1

" Table Of Contents Tools:
function! atplib#tools#getlinenr(...) "{{{
    let line 	=  a:0 >= 1 ? a:1 : line('.')
    let labels 	=  a:0 >= 2 ? a:2 : expand("%") == "__Labels__" ? 1 : 0

    if labels == 0
	let bnr = bufnr("__ToC__")
	if len(getbufvar(bnr, "atp_Toc"))
	    return get(getbufvar(bnr, "atp_Toc"), line, ["", ""])[0:1]
	endif
    else
	let bnr = bufnr("__Labels__")
	let dict=getbufvar(bnr, "atp_Labels")
	if len(dict)
	    return get(dict, line, ["", ""])[0:1]
	endif
    endif
endfunction "}}}
function! atplib#tools#CursorLine() "{{{
    if exists("t:cursorline_idmatch")
	try
	    call matchdelete(t:cursorline_idmatch)
	catch /E803:/
	endtry
    endif
    if expand("%:t") == "__ToC__" && atplib#tools#getlinenr(line(".")) != ['', '']
            let t:cursorline_idmatch =  matchadd('CursorLine', '^\%'.line(".").'l.*$')
        endif
	return
    elseif expand("%:t")) = '__Labels__' && atplib#tools#getlinenr(line(".")) != ['', '']
	let t:cursorline_idmatch =  matchadd('CursorLine', '^\%'.line(".").'l.*$')
	return
    endif
endfunction "}}}

function! atplib#tools#TexDef(bang,args) "{{{1
    let flavor = ( &l:ft == 'plaintex' ? 'tex' : ( &l:ft == 'contex' ? 'contex' : ( &l:ft == 'tex' ? 'latex' : '' ) ) )
    if flavor != ''
	let flavor_op = '--tex '.flavor
    else
	let flavor_op = ''
    endif
    if a:bang == "!"
	if &l:ft == 'tex'
	    let class  = matchstr(get(filter(readfile(atplib#FullPath(b:atp_MainFile))[0:9], 'v:val =~ ''^[^%]*\\documentclass'''), 0, '\documentclass{NOLTXCLASS}'), '\\documentclass\s*\(\[[^\]]*\]\)\?\s*{\s*\zs[^}]*\ze\s*}')
	endif
	let class_op = ( &l:ft == 'tex' && class != 'NOLTXCLASS' ? ' --class '.class : '' )
	if &ft == 'tex' 
	    let load_packages = ''
	    for p in filter(copy(g:atp_packages), 'v:val !~ ''babel\|beamer\|standard_classes\|common\|bibunits\|bibref\|memoir\|a\?article\|a\?book\|biblatex''')
		let load_packages .= ( load_packages == '' ? p : ','.p )
	    endfor
	    let packages = matchstr(a:args, '\s\+-p\s\+\zs\S*\ze')
	    let load_packages.= ( len(packages) ? ','.packages : '' )
	    let args = substitute(a:args, '\s-p\s\+\S*', ' ', 'g')
	    let texdef = 'texdef '.flavor_op.class_op.( len(load_packages) ? ' --package '.load_packages : '').' '.args.''
	else
	    let texdef = 'texdef '.flavor_op.class_op.a:args.''
	endif
    else
	let texdef = 'texdef '.flavor_op.' '.a:args
    endif
    echo texdef."\n".system(texdef)
endfunction "}}}1
" vim:fdm=marker:ff=unix:noet:ts=8:sw=4:fdc=1
autoload/atplib/various.vim	[[[1
2567
" Author:      Marcin Szamotulski	
" Descriptiion:	These are various editting tools used in ATP.
" Note:	       This file is a part of Automatic Tex Plugin for Vim.
" Language:    tex
" Last Change: Sat Apr 28, 2012 at 08:40:02  +0100

let s:sourced 	= exists("s:sourced") ? 1 : 0

" This is the wrap selection function.
" {{{ WrapSelection
function! atplib#various#WrapSelection(...)

    let wrapper		= ( a:0 >= 1 ? a:1 : '{' )
    let end_wrapper 	= ( a:0 >= 2 ? a:2 : '}' )
    if a:0 >=6 && a:6 || a:0 <= 5
	if a:0 <= 5 || a:6 == 1 
	    let s:lastwrapper_begin	= [ wrapper, wrapper ]
	    let s:lastwrapper_end	= [ end_wrapper, end_wrapper ]
	elseif a:6 == 2
	    " Change only text wrapper:
	    if exists("s:lastwrapper_begin")
		let s:lastwrapper_begin[0] = wrapper
		let s:lastwrapper_end[0] = wrapper
	    else
		let s:lastwrapper_begin	= [ wrapper, wrapper ]
		let s:lastwrapper_end	= [ end_wrapper, end_wrapper ]
	    endif
	elseif a:6 == 3
	    " Change only math wrapper:
	    if exists("s:lastwrapper_begin")
		let s:lastwrapper_begin[1] = wrapper
		let s:lastwrapper_end[1] = wrapper
	    else
		let s:lastwrapper_begin	= [ wrapper, wrapper ]
		let s:lastwrapper_end	= [ end_wrapper, end_wrapper ]
	    endif
	endif
    endif
    let cursor_pos	= ( a:0 >= 3 ? a:3 : 'end' )
    let s:lastwrapper_cursor_pos = cursor_pos
    let new_line	= ( a:0 >= 4 ? a:4 : 0 )
    let s:lastwrapper_new_line = new_line
    let marks		= ( a:0 >= 5 ? a:5 : ["'<", "'>"])

"     let b:new_line=new_line
"     let b:cursor_pos=cursor_pos
"     let b:end_wrapper=end_wrapper

    let l:begin=getpos(marks[0])
    " todo: if and on 'ą' we should go one character further! (this is
    " a multibyte character)
    let l:end=getpos(marks[1])
    let l:pos_save=getpos(".")

    " hack for that:
    let l:pos=deepcopy(l:end)
    keepjumps call setpos(".",l:end)
    execute 'normal l'
    let l:pos_new=getpos(".")
    if l:pos_new[2]-l:pos[2] > 1
	let l:end[2]+=l:pos_new[2]-l:pos[2]-1
    endif

    let l:begin_line=getline(l:begin[1])
    let l:end_line=getline(l:end[1])

    " ToDo: this doesn't work yet!
    let l:add_indent='    '
    if l:begin[1] != l:end[1]
	let l:bbegin_line=strpart(l:begin_line,0,l:begin[2]-1)
	let l:ebegin_line=strpart(l:begin_line,l:begin[2]-1)

	" DEBUG
	let b:bbegin_line=l:bbegin_line
	let b:ebegin_line=l:ebegin_line

	let l:bend_line=strpart(l:end_line,0,l:end[2])
	let l:eend_line=strpart(l:end_line,l:end[2])

	if new_line == 0
	    " inline
	    let l:begin_line=l:bbegin_line.wrapper.l:ebegin_line
	    let l:end_line=l:bend_line.end_wrapper.l:eend_line
	    call setline(l:begin[1],l:begin_line)
	    call setline(l:end[1],l:end_line)
	    let l:end[2]+=len(end_wrapper)
	else
	    " in seprate lines
	    let l:indent=atplib#complete#CopyIndentation(l:begin_line)
	    if l:bbegin_line !~ '^\s*$'
		let l:begin_choice=1
		call setline(l:begin[1],l:bbegin_line)
		call append(l:begin[1],l:indent.wrapper) " THERE IS AN ISSUE HERE!
		call append(copy(l:begin[1])+1,l:indent.substitute(l:ebegin_line,'^\s*','',''))
		let l:end[1]+=2
	    elseif l:bbegin_line =~ '^\s\+$'
		let l:begin_choice=2
		call append(l:begin[1]-1,l:indent.wrapper)
		call append(l:begin[1],l:begin_line.l:ebegin_line)
		let l:end[1]+=2
	    else
		let l:begin_choice=3
		call append(copy(l:begin[1])-1,l:indent.wrapper)
		let l:end[1]+=1
	    endif
	    if l:eend_line !~ '^\s*$'
		let l:end_choice=4
		call setline(l:end[1],l:bend_line)
		call append(l:end[1],l:indent.end_wrapper)
		call append(copy(l:end[1])+1,l:indent.substitute(l:eend_line,'^\s*','',''))
	    else
		let l:end_choice=5
		call append(l:end[1],l:indent.end_wrapper)
	    endif
	    if (l:end[1] - l:begin[1]) >= 0
		if l:begin_choice == 1
		    let i=2
		elseif l:begin_choice == 2
		    let i=2
		elseif l:begin_choice == 3 
		    let i=1
		endif
		if l:end_choice == 5 
		    let j=l:end[1]-l:begin[1]+1
		else
		    let j=l:end[1]-l:begin[1]+1
		endif
		while i < j
		    " Adding indentation doesn't work in this simple way here?
		    " but the result is ok.
		    call setline(l:begin[1]+i,l:indent.l:add_indent.getline(l:begin[1]+i))
		    let i+=1
		endwhile
	    endif
	    let l:end[1]+=2
	    let l:end[2]=1
	endif
    else
	let l:begin_l=strpart(l:begin_line,0,l:begin[2]-1)
	let l:middle_l=strpart(l:begin_line,l:begin[2]-1,l:end[2]-l:begin[2]+1)
	let l:end_l=strpart(l:begin_line,l:end[2])
	if new_line == 0
	    " inline
	    let l:line=l:begin_l.wrapper.l:middle_l.end_wrapper.l:end_l
	    call setline(l:begin[1],l:line)
	    let l:end[2]+=len(wrapper)+1
	else
	    " in seprate lines
	    let l:indent=atplib#complete#CopyIndentation(l:begin_line)

	    if l:begin_l =~ '\S' 
		call setline(l:begin[1],l:begin_l)
		call append(copy(l:begin[1]),l:indent.wrapper)
		call append(copy(l:begin[1])+1,l:indent.l:add_indent.l:middle_l)
		call append(copy(l:begin[1])+2,l:indent.end_wrapper)
		if substitute(l:end_l,'^\s*','','') =~ '\S'
		    call append(copy(l:begin[1])+3,l:indent.substitute(l:end_l,'^\s*','',''))
		endif
	    else
		call setline(copy(l:begin[1]),l:indent.wrapper)
		call append(copy(l:begin[1]),l:indent.l:add_indent.l:middle_l)
		call append(copy(l:begin[1])+1,l:indent.end_wrapper)
		if substitute(l:end_l,'^\s*','','') =~ '\S'
		    call append(copy(l:begin[1])+2,l:indent.substitute(l:end_l,'^\s*','',''))
		endif
	    endif
	endif
    endif
    if cursor_pos == "end"
	let l:end[2]+=len(end_wrapper)-1
	call setpos(".",l:end)
    elseif cursor_pos =~ '\d\+'
	let l:pos=l:begin
	let l:pos[2]+=cursor_pos
	call setpos(".",l:pos)
    elseif cursor_pos == "current"
	keepjumps call setpos(".",l:pos_save)
    elseif cursor_pos == "begin"
	let l:begin[2]+=len(wrapper)-1
	keepjumps call setpos(".",l:begin)
    endif
endfunction
" }}}
" {{{ RedoLastWrapSelection
function! atplib#various#RedoLastWrapSelection(marks)
    if !exists("s:lastwrapper_begin")
	echo "[ATP:] no last wrapper."
	return
    endif
    if atplib#IsInMath()
	let lastwrapper_begin 	= s:lastwrapper_begin[1]
	let lastwrapper_end 	= s:lastwrapper_end[1]
    else
	let lastwrapper_begin 	= s:lastwrapper_begin[0]
	let lastwrapper_end 	= s:lastwrapper_end[0]
    endif
    call atplib#various#WrapSelection(lastwrapper_begin, lastwrapper_end,s:lastwrapper_cursor_pos,s:lastwrapper_new_line,a:marks,0)
endfunction
function! atplib#various#WrapSelection_compl(ArgLead, CmdLine, CursorPos)
    let variables = ["g:atp_Commands"]
    if searchpair('\\begin\s*{picture}','','\\end\s*{picture}','bnW',"", max([ 1, (line(".")-g:atp_completion_limits[2])]))
	call add(variables, "g:atp_picture_commands")
    endif
    if atplib#search#SearchPackage('hyperref')
	call add(variables, "g:atp_package_hyperref_commands")
    endif
    if atplib#IsInMath()
	call add(variables, "g:atp_math_commands_PRE")
	call add(variables, "g:atp_math_commands")
	call add(variables, "g:atp_math_commands_non_expert_mode")
	call add(variables, "g:atp_amsmath_commands")
    endif
    if atplib#search#SearchPackage("fancyhdr")
	call add(variables, "g:atp_fancyhdr_commands")
    endif
    if atplib#search#SearchPackage("makeidx")
	call add(variables, "g:atp_makeidx_commands")
    endif
"     Tikz dosn't have few such commands (in libraries)
"     if atplib#search#SearchPackage(#\(tikz\|pgf\)')
" 	let in_tikz=searchpair('\\begin\s*{tikzpicture}','','\\end\s*{tikzpicture}','bnW',"", max([1,(line(".")-g:atp_completion_limits[2])])) || atplib#complete#CheckOpened('\\tikz{','}',line("."),g:atp_completion_limits[0])
" 	    call add(variables, "g:atp_tikz_commands")
" 	endif
"     endif
    if atplib#search#DocumentClass(b:atp_MainFile) == "beamer"
	call add(variables, "g:atp_package_beamer_commands")
    endif
    if atplib#search#SearchPackage("mathtools")
	call add(variables, "g:atp_package_mathtools_commands")
    endif
    if atplib#search#SearchPackage("todonotes")
	call add(variables, "g:atp_TodoNotes_commands")
    endif
"     if !exists("b:atp_LocalCommands")
" 	call LocalCommands(0)
"     endif
    call add(variables, "b:atp_LocalCommands")

    let wrap_commands=[]
    for var in variables
	call extend(wrap_commands, filter(copy({var}), "v:val =~ '{$'"))
    endfor
    call filter(wrap_commands, "count(wrap_commands, v:val) == 1")
    call sort(wrap_commands)
    return join(wrap_commands, "\n")
endfunction
"}}}
"{{{ Inteligent Wrap Selection 
" This function selects the correct font wrapper for math/text environment.
" the rest of arguments are the same as for WrapSelection (and are passed to
" WrapSelection function)
" a:text_wrapper	= [ 'begin_text_wrapper', 'end_text_wrapper' ] 
" a:math_wrapper	= [ 'begin_math_wrapper', 'end_math_wrapper' ] 
" if end_(math\|text)_wrapper is not given '}' is used (but neverthe less both
" arguments must be lists).
function! atplib#various#InteligentWrapSelection(text_wrapper, math_wrapper, ...)

    let cursor_pos	= ( a:0 >= 1 ? a:1 : 'end' )
    let new_line	= ( a:0 >= 2 ? a:2 : 0 )
    let marks		= ( a:0 >= 3 ? a:3 : ["'<", "'>"] )

    if atplib#IsInMath()
	let begin_wrapper 	= a:math_wrapper[0]
	let end_wrapper 	= get(a:math_wrapper,1, '}')
    else
	let begin_wrapper	= a:text_wrapper[0]
	let end_wrapper		= get(a:text_wrapper,1, '}')
    endif
    let s:lastwrapper_begin 	= [ a:text_wrapper[0], a:math_wrapper[0] ]
    let s:lastwrapper_end 	= [ get(a:text_wrapper,1, '}'), get(a:math_wrapper,1, '}') ]

    " if the wrapper is empty return
    " useful for wrappers which are valid only in one mode.
    if begin_wrapper == ""
	return
    endif

    call atplib#various#WrapSelection(begin_wrapper, end_wrapper, cursor_pos, new_line, marks,0) 
endfunction
"}}}
" WrapEnvironment "{{{
" a:1 = 0 (or not present) called by a command
" a:1 = 1 called by a key map (ask for env)
function! atplib#various#WrapEnvironment(...)
    let env_name = ( a:0 == 0 ? '' : a:1 )
    let map = ( a:0 <= 1 ? 0 : a:2 ) 
    if !map
	execute "'<,'>Wrap \\begin{".escape(env_name, ' ')."} \\end{".escape(env_name, ' ')."} 0 1"
	if env_name == ""
	    call search("{") 
	else
	    call search('\\end{'.env_name.'}', 'e')
	endif
    else
	let envs=sort(filter(EnvCompletion("","",""), "v:val !~ '\*$' && v:val != 'thebibliography'"))
	" adjust the list - it is too long.
	let envs_a=copy(envs)
	call map(envs_a, "index(envs_a, v:val)+1.'. '.v:val")
	for line in atplib#PrintTable(envs_a,3)
	    echo line
	endfor
	let envs_a=['Which environment to use:']+envs_a
	let env=input("Which environment to use? type number and press <enter> or type environemnt name, <tab> to complete, <none> for exit:\n","","customlist,EnvCompletion")
	let g:env=env
	if env == ""
	    return
	elseif env =~ '^\d\+$'
	    let env_name=get(envs, env-1, '')
	    if env_name == ''
		return
	    endif
	else
	    let env_name=env
	endif
	call atplib#various#WrapSelection('\begin{'.env_name.'}','\end{'.env_name.'}','0', '1')
    endif
endfunction "}}}
" Unwrap {{{
function! atplib#various#Unwrap()
    
    " If the character under the cursor is not a bracket return:
    if getline(".")[col(".")-1] !~ '\%(\[\|\]\|{\|}\|(\|)\)'
	return
    endif

    let pos_0=getpos(".")
    let before = strpart(getline("."), 0, col(".")-1)
    if before =~ '\\\%(left\|right\|[Bb]igg\=[lr]\)\\$' && getline(".")[col(".")-1] =~ '[{}]'
	let rem = 2
    elseif before =~ '\\$\|\\\%(left\|right\|[Bb]igg\=[lr]\)$'
	let rem = 1
    else
	let rem = 0
    endif
    normal %
    let pos_1 = getpos(".")

    " First delete the closing bracket:
    if pos_1[1] < pos_0[1] || pos_1[1] == pos_0[1] && pos_1[2] < pos_0[2]
	call cursor(pos_0[1], pos_0[2])
    endif
    if rem == 1
	normal! vF\x
    elseif rem == 2
	normal! v2F\x
    else
	normal! x
    endif

    " Now delete the opening one:
    if pos_1[1] < pos_0[1] || pos_1[1] == pos_0[1] && pos_1[2] < pos_0[2]
	call cursor(pos_1[1], pos_1[2])
    else
	call cursor(pos_0[1], pos_0[2])
    endif
    if rem == 1
	normal! vF\x
    elseif rem == 2
	normal! v2F\x
    else
	normal! x
    endif
endfunction "}}}
" SetUpdateTimes "{{{
function! atplib#various#UpdateTime(...)
    if a:0 == 0
	" Show settings
	echo "'updatetime' is set to:\nb:atp_updatetime_normal=".b:atp_updatetime_normal."\nb:atp_updatetime_insert=".b:atp_updatetime_insert
	return
    else
	let b:atp_updatetime_normal=a:1
	let b:atp_updatetime_insert=(a:0>=2 ? a:2 : a:1)
	echo "'updatetime' is set to:\nb:atp_updatetime_normal=".b:atp_updatetime_normal."\nb:atp_updatetime_insert=".b:atp_updatetime_insert
    endif
endfunction "}}}
" Inteligent Aling
" TexAlign {{{
" This needs Aling vim plugin.
function! atplib#various#TexAlign(bang)
    let save_pos = getpos(".")
    let winsaveview = winsaveview()
    let synstack = map(synstack(line("."), col(".")), 'synIDattr( v:val, "name")')

    let barray=searchpair('\\begin\s*{\s*array\s*}', '', '\\end\s*{\s*array\s*}', 'bnW', '',max([1,line('.')-500]))
    let bsmallmatrix=searchpair('\\begin\s*{\s*smallmatrix\s*}', '', '\\end\s*{\s*smallmatrix\s*}', 'bnW', '',max([1,line('.')-500]))
"     let [bmatrix, bmatrix_col]=searchpairpos('\\matrix\s*\%(\[[^]]*\]\s*\)\=\zs{', '', '}', 'bnW', '', max([1, (line(".")-g:atp_completion_limits[2])]))
    let [bmatrix, bmatrix_col]=searchpos('^\%([^%]\|\\%\)*\\matrix\s*\%(\[[^]]*\]\s*\)\=\zs{', 'bW', max([1, (line(".")-g:atp_completion_limits[2])]))
    if bmatrix != 0
	normal %
	let bmatrix = ( line(".") >= save_pos[1] ? bmatrix : 0 )
	call cursor(save_pos[1], save_pos[2])
    endif
    if bmatrix
	let bpat = '\\matrix\s*\(\[[^\]]*\]\)\?\s*{'
	let bline = bmatrix+1 
	let epat = '}'
	let AlignCtr = 'l+'
	let AlignSep = '&\|\\pgfmatrixnextcell'
	let env = "matrix"
    elseif barray
	let bpat = '\\begin\s*{\s*array\s*}'
	let bline = barray+1
	let epat = '\\end\s*{\s*array\s*}'
	let AlignCtr = 'l+'
	let AlignSep = '&'
	let env = "array"
    elseif bsmallmatrix
	let bpat = '\\begin\s*{\s*smallmatrix\s*}'
	let bline = bsmallmatrix+1
	let epat = '\\end\s*{\s*smallmatrix\s*}'
	let AlignCtr = 'l+'
	let AlignSep = '&'
	let env = "smallmatrix"
    elseif count(synstack, 'texMathZoneA') || count(synstack, 'texMathZoneAS')
	let bpat = '\\begin\s*{\s*align\*\=\s*}' 
	let epat = '\\end\s*{\s*align\*\=\s*}' 
	let AlignCtr = 'l+'
	let AlignSep = '&'
	let AlignCtrV = '^\s*\\intertext'
	let env = "align"
    elseif count(synstack, 'texMathZoneB') || count(synstack, 'texMathZoneBS')
	let bpat = '\\begin\s*{\s*alignat\*\=\s*}' 
	let epat = '\\end\s*{\s*alignat\*\=\s*}' 
	let AlignCtr = 'l+'
	let AlignSep = '&'
	let env = "alignat"
    elseif count(synstack, 'texMathZoneD') || count(synstack, 'texMathZoneDS')
	let bpat = '\\begin\s*{\s*eqnarray\*\=\s*}' 
	let epat = '\\end\s*{\s*eqnarray\*\=\s*}' 
	let AlignCtr = 'l+'
	let AlignSep = '&'
	let env = "eqnarray"
    elseif count(synstack, 'texMathZoneE') || count(synstack, 'texMathZoneES')
	let bpat = '\\begin\s*{\s*equation\*\=\s*}' 
	let epat = '\\end\s*{\s*equation\*\=\s*}' 
	let AlignCtr = 'l+'
	let AlignSep = '= + -'
	let env = "equation"
    elseif count(synstack, 'texMathZoneF') || count(synstack, 'texMathZoneFS')
	let bpat = '\\begin\s*{\s*flalign\*\=\s*}' 
	let epat = '\\end\s*{\s*flalign\*\=\s*}' 
	let AlignCtr = 'l+'
	let AlignSep = '&'
	let env = "falign"
"     elseif count(synstack, 'texMathZoneG') || count(synstack, 'texMathZoneGS')
"     gather doesn't need alignment (by design it give unaligned equation.
" 	let bpat = '\\begin\s*{\s*gather\*\=\s*}' 
" 	let epat = '\\end\s*{\s*gather\*\=\s*}' 
" 	let AlignCtr = 'Il+ &'
" 	let env = "gather"
    elseif count(synstack, 'displaymath')
	let bpat = '\\begin\s*{\s*displaymath\*\=\s*}' 
	let epat = '\\end\s*{\s*displaymath\*\=\s*}' 
	let AlignCtr = 'l+'
	let AlignSep = '= + -'
	let env = "displaymath"
    elseif searchpair('\\begin\s*{\s*tabular\s*\}', '', '\\end\s*{\s*tabular\s*}', 'bnW', '', max([1, (line(".")-g:atp_completion_limits[2])]))
	let bpat = '\\begin\s*{\s*tabular\*\=\s*}' 
	let epat = '\\end\s*{\s*tabular\*\=\s*}' 
	let AlignCtr = 'l+'
	let AlignSep = '&'
	let env = "tabular"
    elseif searchpair('\\begin\s*{\s*\%(long\)\=table\s*\}', '', '\\end\s*{\s*\%(long\)\=table\s*}', 'bnW', '', max([1, (line(".")-g:atp_completion_limits[2])]))
	let bpat = '\\begin\s*{\s*\%(long\)\=table\*\=\s*}' 
	let epat = '\\end\s*{\s*\%(long\)\=table\*\=\s*}' 
	let AlignCtr = 'l+'
	let AlignSep = '&'
	let env = "table"
    else
	return
    endif

    if !exists("bline")
	let bline = search(bpat, 'cnb') + 1
    endif
    if env != "matrix"
	let eline = searchpair(bpat, '', epat, 'cn')  - 1
    else
	let saved_pos = getpos(".")
	call cursor(bmatrix, bmatrix_col)
	let eline = searchpair('{', '', '}', 'n')  - 1
	call cursor(saved_pos[1], saved_pos[2])
    endif

    if a:bang == "!" && eline-1 > bline
	" Join lines (g:atp_TexAlign_join_lines)
	execute 'keepjumps silent! '.(bline).','.(eline-1).'g/\%(\\\\\s*\%(\[[^\]]*\]\|\\hline\|\\hrule\)*\s*\|\\intertext.*\)\@<!\n/s/\n//'
	call histdel("search", -1)
	let @/ = histget("search", -1)
	if env != "matrix"
	    let eline = searchpair(bpat, '', epat, 'cn')  - 1
	else
	    let saved_pos = getpos(".")
	    call cursor(bmatrix, bmatrix_col)
	    let eline = searchpair('{', '', '}', 'n')  - 1
	    call cursor(saved_pos[1], saved_pos[2])
	endif
    endif

    if bline <= eline
	call Align#AlignCtrl(AlignCtr)
	if exists("AlignCtrV")
	    call Align#AlignCtrl('v '.AlignCtrV)
	endif
	execute bline . ',' . eline . 'Align ' .AlignSep
	if exists("AlignCtrV")
	    AlignCtrl v
	endif
    endif

    call setpos(".", save_pos) 
    call winrestview(winsaveview)
endfunction
"}}}
" Editing Toggle Functions
"{{{ ToggleStar
" this function adds a star to the current environment
" todo: to doc.
function! atplib#various#ToggleStar()

    " limit:
    let from_line=max([1,line(".")-g:atp_completion_limits[2]])
    let to_line=line(".")+g:atp_completion_limits[2]

    " omit pattern
    let no_star=copy(g:atp_no_star_environments)
    let cond = atplib#search#SearchPackage('mdwlist')
    if cond || exists("b:atp_LocalEnvironments") && index(b:atp_LocalEnvironments, 'enumerate*') != -1
	call remove(no_star, index(no_star, 'enumerate'))
    endif
    if cond || exists("b:atp_LocalEnvironments") && index(b:atp_LocalEnvironments, 'itemize') != -1
	call remove(no_star, index(no_star, 'itemize'))
    endif
    if cond || exists("b:atp_LocalEnvironments") && index(b:atp_LocalEnvironments, 'description') != -1
	call remove(no_star, index(no_star, 'description'))
    endif
    let omit=join(no_star,'\|')
    let open_pos=searchpairpos('\\begin\s*{','','\\end\s*{[^}]*}\zs','cbnW','getline(".") =~ "\\\\begin\\s*{".omit."}"',from_line)
    let env_name=matchstr(strpart(getline(open_pos[0]),open_pos[1]),'begin\s*{\zs[^}]*\ze}')
    if ( open_pos == [0, 0] || index(no_star, env_name) != -1 ) && getline(line(".")) !~ '\\\%(part\|chapter\|\%(sub\)\{0,2}section\)'
	return
    endif
    if env_name =~ '\*$'
	let env_name=substitute(env_name,'\*$','','')
	let close_pos=searchpairpos('\\begin\s*{'.env_name.'\*}','','\\end\s*{'.env_name.'\*}\zs','cnW',"",to_line)
	if close_pos != [0, 0]
	    call setline(open_pos[0],substitute(getline(open_pos[0]),'\(\\begin\s*{\)'.env_name.'\*}','\1'.env_name.'}',''))
	    call setline(close_pos[0],substitute(getline(close_pos[0]),
			\ '\(\\end\s*{\)'.env_name.'\*}','\1'.env_name.'}',''))
	    echomsg "[ATP:] star removed from '".env_name."*' at lines: " .open_pos[0]." and ".close_pos[0]
	endif
    else
	let close_pos=searchpairpos('\\begin\s{'.env_name.'}','','\\end\s*{'.env_name.'}\zs','cnW',"",to_line)
	if close_pos != [0, 0]
	    call setline(open_pos[0],substitute(getline(open_pos[0]),
		    \ '\(\\begin\s*{\)'.env_name.'}','\1'.env_name.'\*}',''))
	    call setline(close_pos[0],substitute(getline(close_pos[0]),
			\ '\(\\end\s*{\)'.env_name.'}','\1'.env_name.'\*}',''))
	    echomsg "[ATP:] star added to '".env_name."' at lines: " .open_pos[0]." and ".close_pos[0]
	endif
    endif

    " Toggle the * in \section, \chapter, \part commands.
    if getline(line(".")) =~ '\\\%(part\|chapter\|\%(sub\)\{0,2}section\)\*'
	let pos = getpos(".")
	substitute/\(\\part\|\\chapter\|\\\%(sub\)\{0,2}section\)\*/\1/
	call cursor(pos[1], pos[2])
    elseif getline(line(".")) =~ '\\\%(part\|chapter\|\%(sub\)\{0,2}section\)'
	let pos = getpos(".")
	substitute/\(\\part\|\\chapter\|\\\%(sub\)\{0,2}section\)/\1*/
	call cursor(pos[1], pos[2])
    endif
endfunction
"}}}
"{{{ ToggleEnvironment
" this function toggles envrionment name.
" Todo: to doc.
" a:ask = 0 toggle, 1 ask for the new env name if not given as the first argument. 
" the argument specifies the speed (if -1 then toggle back)
" default is '1' or the new environment name
try
function! atplib#various#ToggleEnvironment(ask, ...)

    let atp_MainFile	= atplib#FullPath(b:atp_MainFile)
    " add might be a number or an environment name
    " if it is a number the function will jump this amount in appropriate list
    " (g:atp_toggle_environment_[123...]) to find new environment name
    let add = ( a:0 >= 1 ? a:1 : 1 ) 

    " limit:
    let from_line=max([1,line(".")-g:atp_completion_limits[2]])
    let to_line=line(".")+g:atp_completion_limits[2]

    " omit pattern
    let omit=join(g:atp_no_toggle_environments,'\|')
    let open_pos=searchpairpos('\\begin\s*{','','\\end\s*{[^}]*}\zs','bcnW','getline(".") =~ "\\\\begin\\s*{".omit."}"',from_line)
    let env_name=matchstr(strpart(getline(open_pos[0]),open_pos[1]),'begin\s*{\zs[^}]*\ze}')

    let label=matchstr(strpart(getline(open_pos[0]),open_pos[1]),'\\label\s*{\zs[^}]*\ze}')
    if open_pos == [0, 0] || index(g:atp_no_toggle_environments,env_name) != -1
	return
    endif

    let env_name_ws=substitute(env_name,'\*$','','')

    if !a:ask
	let variable="g:atp_toggle_environment_1"
	let i=1
	while 1
	    let env_idx=index({variable},env_name_ws)
	    if env_idx != -1
		break
	    else
		let i+=1
		let variable="g:atp_toggle_environment_".i
	    endif
	    if !exists(variable)
		return
	    endif
	endwhile

	if add > 0 && env_idx > len({variable})-add-1
	    let env_idx=0
	elseif ( add < 0 && env_idx < -1*add )
	    let env_idx=len({variable})-1
	else
	    let env_idx+=add
	endif
	let new_env_name={variable}[env_idx]
	if env_name =~ '\*$'
	    let new_env_name.="*"
	endif
    else
	if add == 1
	    let new_env_name=input("What is the new name for " . env_name . "? type and hit <Enter> ", "", "customlist,EnvCompletion" )
	    if new_env_name == ""
		redraw
		echomsg "[ATP:] environment name not changed"
		return
	    endif
	else
	    let new_env_name = add
	endif
    endif

    let env_name=escape(env_name,'*')
    let close_pos=searchpairpos('\\begin\s*{'.env_name.'}','','\\end\s*{'.env_name.'}\zs','nW',"",to_line)
    if close_pos != [0, 0]
	call setline(open_pos[0],substitute(getline(open_pos[0]),'\(\\begin\s*{\)'.env_name.'}','\1'.new_env_name.'}',''))
	call setline(close_pos[0],substitute(getline(close_pos[0]),
		    \ '\(\\end\s*{\)'.env_name.'}','\1'.new_env_name.'}',''))
	redraw
	echomsg "[ATP:] environment toggeled at lines: " .open_pos[0]." and ".close_pos[0]
    endif

    if label != "" && g:atp_toggle_labels
	if env_name == ""
	    let new_env_name_ws=substitute(new_env_name,'\*$','','')
	    let new_short_name=get(g:atp_shortname_dict,new_env_name_ws,"")
	    let new_label =  new_short_name . strpart(label, stridx(label, g:atp_separator))
	else
	    let new_env_name_ws=substitute(new_env_name,'\*$','','')
	    let new_short_name=get(g:atp_shortname_dict,new_env_name_ws,"")
	    let short_pattern= '^\(\ze:\|' . join(values(filter(g:atp_shortname_dict,'v:val != ""')),'\|') . '\)'
	    let short_name=matchstr(label, short_pattern)
	    let new_label=substitute(label,'^'.short_name,new_short_name,'')
	endif


	" check if new label is in use!
	let pos_save=getpos(".")

	" Test if the new label exists.
	let test = search('\m\C\\label\s*{'.new_label.'}','nwc')

	if !test && new_label != label
	    let hidden = &hidden
	    set hidden
	    silent! keepjumps execute open_pos[0].'substitute /\\label{'.label.'}/\\label{'.new_label.'}'
	    " This should be done for every file in the project. 
	    if !exists("b:TypeDict")
		call TreeOfFiles(atp_MainFile)
	    endif
	    let save_view 	= winsaveview()
	    let file		= expand("%:p")
	    let project_files = keys(filter(b:TypeDict, "v:val == 'input'")) + [ atp_MainFile ]
	    for project_file in project_files
		let bufloaded = bufloaded(project_file)
		if atplib#FullPath(project_file) != expand("%:p")
		    exe "silent keepalt edit " . project_file
		endif
		let pos_save_pf=getpos(".")
		silent! keepjumps execute '%substitute /\\\(eq\|page\)\?\(ref\s*\){'.label.'}/\\\1\2{'.new_label.'}/gIe'
		" Write the file: 
" 		update
" 		if !bufloaded
" 		    silent! bd
" 		endif
		keepjumps call setpos(".", pos_save_pf)
	    endfor
	    execute "keepalt buffer " . file
	    keepjumps call setpos(".", pos_save)
	    let &hidden = hidden
	elseif test && new_label != label
	    redraw
	    echohl WarningMsg
	    echomsg "[ATP:] labels not changed, new label: ".new_label." is in use!"
	    echohl None
	endif
    endif
    return  open_pos[0]."-".close_pos[0]
endfunction
catch /E127:/
endtry "}}}
" {{{ ChangeLabel
function! atplib#various#ChangeLabel(new_label)
    let atp_MainFile	= atplib#FullPath(b:atp_MainFile)
    let pos_save=getpos(".")
    let view = winsaveview()

    let label  = matchstr(getline(line(".")), '\\label\s*{\zs[^}]*\ze}')
    if label == ""
	echohl WarningMsg
	echo "[ATP:] \\label command not found in the current line."
	echohl None
	return
    endif
    let hidden = &hidden
    set hidden
    let save_view 	= winsaveview()
    execute 's/\\label{'.label.'}/\\label{'.a:new_label.'}/'
    " This should be done for every file in the project. 
    if !exists("b:TypeDict")
	call TreeOfFiles(atp_MainFile)
    endif
    let file		= expand("%:p")
    let project_files = keys(filter(b:TypeDict, "v:val == 'input'")) + [ atp_MainFile ]
    for project_file in project_files
	let bufloaded = bufloaded(project_file)
	if atplib#FullPath(project_file) != expand("%:p")
	    exe "silent keepalt edit " . project_file
	endif
	let pos_save_pf=getpos(".")
	silent! keepjumps execute '%substitute /\\\(eq\|page\)\?\(ref\s*\){'.label.'}/\\\1\2{'.a:new_label.'}/gIe'
	" Write the file: 
" 		update
" 		if !bufloaded
" 		    silent! bd
" 		endif
	keepjumps call setpos(".", pos_save_pf)
    endfor
    execute "keepalt buffer " . file
    keepjumps keepmarks call winrestview(view)
    let &hidden = hidden
endfunction "}}}
" This is completion for input() inside ToggleEnvironment which uses
" b:atp_LocalEnvironments variable.
function! atplib#various#EnvCompletion(ArgLead, CmdLine, CursorPos) "{{{
    if !exists("b:atp_LocalEnvironments")
	call LocalCommands(1)
    endif

    let env_list = copy(b:atp_LocalEnvironments)
    " add standard and ams environment if not present.
    let env_list=atplib#Extend(env_list, g:atp_Environments)
    if atplib#search#SearchPackage('amsmath')
	let env_list=atplib#Extend(env_list, g:atp_amsmath_environments)
    endif
    call filter(env_list, "v:val =~# '^' .a:ArgLead")
    return env_list
endfunction "}}}
function! atplib#various#EnvCompletionWithoutStarEnvs(ArgLead, CmdLine, CursorPos) "{{{
    if !exists("b:atp_LocalEnvironments")
	call LocalCommands(1)
    endif

    let env_list = copy(b:atp_LocalEnvironments)
    " add standard and ams environment if not present.
    let env_list=atplib#Extend(env_list, g:atp_Environments)
    if atplib#search#SearchPackage('amsmath')
	let env_list=atplib#Extend(env_list, g:atp_amsmath_environments)
    endif
    call filter(env_list, "v:val =~# '^' .a:ArgLead")
    return env_list
endfunction "}}}
function! atplib#various#F_compl(ArgLead, CmdLine, CursorPos) "{{{
    " This is like EnvCompletion but without stared environments and with: chapter, section, ...
    if !exists("b:atp_LocalEnvironments")
	call LocalCommands(1)
    endif

    let env_list = copy(b:atp_LocalEnvironments)
    " add standard and ams environment if not present.
    let env_list=atplib#Extend(env_list, g:atp_Environments)
    let env_list=atplib#Extend(env_list, ['part', 'chapter', 'section', 'subsection', 'subsubsection'])
    if atplib#search#SearchPackage('amsmath') || atplib#search#SearchPackage('amsthm')
	let env_list=atplib#Extend(env_list, g:atp_amsmath_environments)
    endif
    call filter(env_list+['math'], "v:val !~ '\*$'")
    return join(env_list, "\n")
endfunction "}}}
" TexDoc commanand and its completion
" {{{ TexDoc 
" This is non interactive !, use :!texdoc for interactive command.
" But it simulates it with a nice command completion (Ctrl-D, <Tab>)
" based on alias files for texdoc.
function! atplib#various#TexDoc(...)
    let texdoc_arg	= ""
    for i in range(1,a:0)
	let texdoc_arg.=" " . a:{i}
    endfor
    if texdoc_arg == ""
	let texdoc_arg 	= g:atp_TeXdocDefault
    endif
    " If the file is a text file texdoc is 'cat'-ing it into the terminal,
    " we use echo to capture the output. 
    " The rediraction prevents showing texdoc info messages which are not that
    " important, if a document is not found texdoc sends a message to the standard
    " output not the error.
    "
    " -I prevents from using interactive menus
    echo system("texdoc " . texdoc_arg . " 2>/dev/null")
endfunction

function! atplib#various#TeXdoc_complete(ArgLead, CmdLine, CursorPos)
    let texdoc_alias_files=split(system("texdoc -f"), '\n')
    call filter(texdoc_alias_files, "v:val =~ 'active'")
    call map(texdoc_alias_files, "substitute(substitute(v:val, '^[^/]*\\ze', '', ''), '\/\/\\+', '/', 'g')")
    let aliases = []
    for file in texdoc_alias_files
	call extend(aliases, readfile(file))
    endfor
    let local_list = map(split(globpath(g:texmf.'/doc', '*'), "\n"), 'fnamemodify(v:val, ":t:r")')

    call filter(aliases, "v:val =~ 'alias'")
    call filter(map(aliases, "matchstr(v:val, '^\\s*alias\\s*\\zs\\S*\\ze\\s*=')"),"v:val !~ '^\\s*$'")
    call extend(aliases, local_list)
    if exists("g:atp_LatexPackages")
	call extend(aliases, g:atp_LatexPackages)
    endif

    return filter(copy(aliases), "v:val =~ '^' . a:ArgLead")
endfunction
" }}}

" This function deletes tex specific output files (exept the pdf/dvi file, unless
" bang is used - then also delets the current output file)
" {{{ Delete
function! atplib#various#Delete(delete_output)

    let atp_MainFile	= atplib#FullPath(b:atp_MainFile)
    call atplib#outdir()

    let atp_tex_extensions=deepcopy(g:atp_tex_extensions)

    if a:delete_output == "!" || g:atp_delete_output == 1
	let ext = substitute(get(g:atp_CompilersDict,b:atp_TexCompiler,""), '^\s*\.', '', 'g')
	if ext != ""
	    call add(atp_tex_extensions,ext)
	endif
    else
	" filter extensions which should not be deleted
	call filter(atp_tex_extensions, "index(g:atp_DeleteWithBang, v:val) == -1")
    endif

    " Be sure that we are not deleting outputs:
    for ext in atp_tex_extensions
	if ext != "pdf" && ext != "dvi" && ext != "ps"
	    let files=split(globpath(fnamemodify(atp_MainFile, ":h"), "*.".ext), "\n")
	    if files != []
		echo "Removing *.".ext
		for f in files
		    call delete(f)
		endfor
	    endif
	else
	    " Delete output file (pdf|dvi|ps) (though ps is not supported by ATP).
	    let f=fnamemodify(atplib#FullPath(b:atp_MainFile), ":r").".".ext
	    echo "Removing ".f
	    call delete(f)
	endif
    endfor
endfunction
"}}}
"{{{ OpenLog, TexLog, TexLog Buffer Options, PdfFonts, YesNoCompletion
"{{{ atplib#various#Search function for Log Buffer
function! atplib#various#Search(pattern, flag, ...)
    echo ""
    let center 	= ( a:0 >= 1 ? a:1 : 1 )
    let @/	= a:pattern

    " Count:
"     let nr 	= 1
"     while nr <= a:count
" 	let keepjumps = ( a:nr < a:count ? 'keepjumps' : '')
" 	exe keepjumps . "let line = search(a:pattern, a:flag)"
" 	let nr	+= 1
"     endwhile

    let line = search(a:pattern, a:flag)

    if !line
	let message = a:flag =~# 'b' ? 'previous' : 'next'
	if a:pattern =~ 'warning'
	    let type = 'warning'
	elseif a:pattern =~ '!$'
	    let type = 'error'
	elseif a:pattern =~ 'info'
	    let type = 'info'
	else
	    let type = ''
	endif
	echohl WarningMsg
	echo "No " . message . " " . type . " message."
	echohl None
    endif
" This fails (?):
"     if center
" 	normal zz
"     endif
endfunction

function! atplib#various#Searchpair(start, middle, end, flag, ...)
    let center 	= ( a:0 >= 1 ? a:1 : 1 )
    if getline(".")[col(".")-1] == ')' 
	let flag= a:flag.'b'
    else
	let flag= substitute(a:flag, 'b', '', 'g')
    endif
    call searchpair(a:start, a:middle, a:end, flag)
"     if center
" 	normal zz
"     endif
endfunction
"}}}
function! atplib#various#OpenLog()
    let errorfile = (g:atp_ParseLog ? substitute(&l:errorfile, '_log$', 'log', '') : &l:errorfile )
    if filereadable(errorfile)

	let projectVarDict = SaveProjectVariables()
	let s:winnr	= bufwinnr("")
	let atp_TempDir	= b:atp_TempDir
	exe "rightbelow split " . fnameescape(errorfile)
	" Settings for the log file are read by plugin/tex_atp.vim
	" autocommand.
	let b:atp_TempDir = atp_TempDir
	call RestoreProjectVariables(projectVarDict)


"	This prevents vim from reloading with 'autoread' option: the buffer is
"	modified outside and inside vim.
	try
	    silent! execute 'keepjumps %g/^\s*$/d'
	    silent! execute "keepjumps normal ''"
	catch /E486:/ 
	endtry
    else
	echo "No log file"
    endif
endfunction
function! atplib#various#SyncXpdfLog(...)

    let atp_MainFile	= atplib#FullPath(b:atp_MainFile)
    " check the value of g:atp_SyncXpdfLog
    let check = ( a:0 >= 1 ? a:1 : 1 )

    if b:atp_Viewer !~ '^\s*xpdf\>' || b:atp_XpdfServer == "" || check && !g:atp_SyncXpdfLog
	return
    endif

    let [ lineNr, colNr ] 	= searchpos('\[\_d\+\%({[^}]*}\)\=\n\=\]', 'n')
    let line 	= strpart(getline(lineNr), colNr-1) . getline(lineNr+1)

    let pageNr	= substitute(matchstr(line, '\[\zs\_d\+\ze\%({[^}]*}\)\=\]'), "\n", "", "g")

    if pageNr	!= ""
	let cmd = "xpdf -remote " . b:atp_XpdfServer . " " . fnamemodify(atp_MainFile, ":r") . ".pdf " . pageNr . " &"
    call system(cmd)
    endif
endfunction
function! atplib#various#SyncTex(bang,...)

    let cwd = getcwd()
    exe "lcd " . fnameescape(b:atp_ProjectDir)

    let g:debugST	= 0

    " if sync = 1 sync log file and the window - can be used by autocommand
    let sync = ( a:0 >= 1 ? a:1 : 0 )
	if g:atp_debugST
	    let g:sync = sync
	endif 

    if sync && !g:atp_LogSync
	exe "normal! " . cwd
	let g:debugST 	= 1
	return
    endif

    " Find the end pos of error msg
    keepjumps let [ stopline, stopcol ] = searchpairpos('(', '', ')', 'nW') 
	if g:atp_debugST
	    let g:stopline = stopline
	endif

    let saved_pos = getpos(".")

    " Be linewise
    call setpos(".", [0, line("."), 1, 0])

    " Find the line nr
" 	    keepjumps let [ LineNr, ColNr ] = searchpos('^l.\zs\d\+\>\|oninput line \zs\|at lines \zs', 'W', stopline)
    keepjumps let [ LineNr, ColNr ] = searchpos('^l.\zs\d\+\>\|o\n\=n\_s\+i\n\=n\n\=p\n\=u\n\=t\_s\+l\n\=i\n\=n\n\=e\_s\+\zs\|a\n\=t\_s\+l\n\=i\n\=n\n\=e\n\=s\_s\+\zs', 'W', stopline)
    let line	= strpart(getline(LineNr), ColNr-1)
    let lineNr 	= matchstr(line, '^\d\+\ze')
	let g:lineNr=lineNr
    if lineNr !~ '\d\+'
	keepjumps call setpos(".", saved_pos)
	return
    endif
    if getline(LineNr) =~ '^l\.\d\+'
	let error = escape(matchstr(getline(LineNr), '^l\.\d\+\s*\zs.*$'), '\.')
" 		let error = escape(matchstr(getline(LineNr), '^l\.\d\+\s*\zs.*$'), '\.') . '\s*' .  escape(substitute(strpart(getline(LineNr+1), 0, stridx(getline(LineNr+1), '...')), '^\s*', '', ''), '\.')
	if g:atp_debugST
	    let g:error = error
	endif
    endif

    " Find the file name/bufnr/winnr where the error occurs. 
    let test 	= 0
    let nr	= 0
    " There should be a finer way to get the file name if it is split in two
    " lines.
    if g:atp_debugST
	let g:fname_list = []
    endif
    while !test
	" Some times in the lof file there is a '(' from the source tex file
	" which might be not closed, then this while loop is used to find
	" readable file name.
	let [ startline, startcol ] = searchpairpos('(', '', ')', 'bW') 
	if g:atp_debugST
	    exe "redir! > ".g:atp_TempDir."/SyncTex.log"
	    let g:startline = startline
	    silent! echomsg " [ startline, startcol ] " . string([ startline, startcol ])
	endif
" THIS CODE IS NOT WORKING:
" 		if nr >= 1 && [ startline, startcol ] == [ startline_o, startcol_o ] && !test
" 		    keepjumps call setpos(".", saved_pos)
" 		    break
" 		endif
	if !startline
	    if g:atp_debugST
		silent! echomsg "END startline = " . startline
		redir END
	    endif
	    keepjumps call setpos(".", saved_pos)
	    return
	endif
	let fname 	= matchstr(strpart(getline(startline), startcol), '^\f\+') 
	" if the file name was broken in the log file in two lines,
	" get the end of file name from the next line. 
	let tex_extensions = extend(copy(g:atp_tex_extensions), [ 'tex', 'cls', 'sty', 'clo', 'def' ], 0)
	let pat = '\.\%('.join(tex_extensions, '\|').'\)$'
	if fname !~# pat
	    let stridx = {}
	    for end in tex_extensions
		call extend(stridx, { end : stridx(getline(startline+1), "." . end) })
	    endfor
	    call filter(stridx, "v:val != -1")
	    let StrIdx = {}
	    for end in keys(stridx)
		call extend(StrIdx, { stridx[end] : end }, 'keep')
	    endfor
	    let idx = min(keys(StrIdx))
	    let end = get(StrIdx, idx, "")
	    let fname .= strpart(getline(startline+1), 0, idx + len(end) + 1)
	endif
	let fname=substitute(fname, escape(fnamemodify(b:atp_TempDir, ":t"), '.').'\/[^\/]*\/', '', '')
	if g:atp_debugST
	    call add(g:fname_list, fname)
	    let g:fname = fname
	    let g:dir	= fnamemodify(g:fname, ":p:h")
	    let g:pat	= pat
" 		    if g:fname =~# '^' .  escape(fnamemodify(tempname(), ":h"), '\/')
" 			let g:fname = substitute(g:fname, fnamemodify(tempname(), ":h"), b:atp_ProjectDir)
" 		    endif
	endif
	let test 	= filereadable(fname)
	let nr	+= 1
	let [ startline_o, startcol_o ] = deepcopy([ startline, startcol ])
    endwhile
    keepjumps call setpos(".", saved_pos)
    if g:atp_debugST
	let g:fname_post = fname
    endif

    " if the file is under texmf directory return unless g:atp_developer = 1
    " i.e. do not visit packages and classes.
    if ( fnamemodify(fname, ':p') =~ '\%(\/\|\\\)texmf' || index(['cls', 'sty', 'bst'], fnamemodify(fname, ":e")) != -1 ) && !g:atp_developer
	keepjumps call setpos(".", saved_pos)
	return
    elseif fnamemodify(fname, ':p') =~ '\%(\/\|\\\)texmf'
	" comma separated list of options
	let options = 'nospell'
    else
	let options = ''
    endif

    let bufnr = bufnr(fname)
" 		let g:bufnr = bufnr
    let bufwinnr	= bufwinnr(bufnr)
    let log_winnr	= bufwinnr("")

    " Goto found file and correct line.
    " with bang open file in a new window,
    " without open file in previous window.
    if a:bang == "!"
	if bufwinnr != -1
	    exe bufwinnr . " wincmd w"
	    exe ':'.lineNr
	    exe 'normal zz'
	elseif buflisted(bufnr)
	    exe 'split #' . bufnr
	    exe ':'.lineNr
	    exe 'normal zz'
	else
	    " allows to go to errrors in packages.
	    exe 'split ' . fname
	    exe ':'.lineNr
	    exe 'normal zz'
	endif
    else
	if bufwinnr != -1
	    exe bufwinnr . " wincmd w"
	    exe ':'.lineNr
	    exe 'normal zz'
	elseif exists("s:winnr")
	    exe s:winnr . " wincmd w"
	    if buflisted(bufnr)
		exe "b " . bufnr
		exe ':'.lineNr
		exe 'normal zz'
	    else
		exe "edit " . fname
		exe ':'.lineNr
		exe 'normal zz'
	    endif
	    exe 'normal zz'
	else
	    if buflisted(bufnr)
		exe "b " . bufnr
		exe ':'.lineNr
		exe 'normal zz'
	    else
		exe "edit " . fname
		exe ':'.lineNr
		exe 'normal zz'
	    endif
	    exe 'normal zz'
	endif
    endif

    " set options
	if &filetype == ""
	    filetype detect
	endif
	for option in split(options, ',')
	    exe "setl " . option
	endfor

    " highlight the error
    if exists("error") && error != ""
	let matchID =  matchadd("Error", error, 15) 
    endif

    if sync
	setl cursorline
	" Unset 'cursorline' option when entering the window. 
	exe 'au! WinEnter ' . expand("%:p")  . " setl nocursorline"
	exe log_winnr . ' wincmd w'
    else
	setl nocursorline
    endif

    exe "lcd " . fnameescape(cwd)
endfunction

" TeX LOG FILE
if &buftype == 'quickfix'
	setlocal modifiable
	setlocal autoread
endif	
function! atplib#various#TexLog(...)
    if executable("texloganalyser")
       let cmd="texloganalyser ".( a:0 ? a:1 : "")." ".shellescape(fnamemodify(atplib#FullPath(b:atp_MainFile),":r").".log")
       echo system(cmd)
    else	
       echo "Please install 'texloganalyser' to have this functionality. The perl program written by Thomas van Oudenhove."  
    endif
endfunction

function! atplib#various#PdfFonts()
    if executable("pdffonts")
	echo system("pdffonts " . fnameescape(fnamemodify(atplib#FullPath(b:atp_MainFile),":r")) . ".pdf")
    else
	echo "Please install 'pdffonts' to have this functionality. In 'gentoo' it is in the package 'app-text/poppler-utils'."  
    endif
endfunction	

" function! atplib#various#setprintexpr()
"     if b:atp_TexCompiler == "pdftex" || b:atp_TexCompiler == "pdflatex"
" 	let s:ext = ".pdf"
"     else
" 	let s:ext = ".dvi"	
"     endif
"     let &printexpr="system('lpr' . (&printdevice == '' ? '' : ' -P' . &printdevice) . ' " . fnameescape(fnamemodify(expand("%"),":p:r")) . s:ext . "') . + v:shell_error"
" endfunction
" call s:setprintexpr()

function! atplib#various#YesNoCompletion(A,P,L)
    return ['yes','no']
endfunction
"}}}
"{{{ Print, Lpstat, ListPrinters
" This function can send the output file to local or remote printer.
" a:1   = file to print		(if not given printing the output file)
" a:3	= printing options	(give printing optinos or 'default' then use
" 				the variable g:printingoptions)
 function! atplib#various#SshPrint(...)

    call atplib#outdir()

    " set the extension of the file to print
    " if prining the tex output file.
    if a:0 == 0 || a:0 >= 1 && a:1 == ""
	let ext = get(g:atp_CompilersDict, b:atp_TexCompiler, "not present")
	if ext == "not present"
	    echohl WarningMsg
	    echomsg "[ATP:] ".b:atp_TexCompiler . " is not present in g:atp_CompilersDict"
	    echohl None
	    return "extension not found"
	endif
	if b:atp_TexCompiler =~ "lua"
	    if b:atp_TexOptions == "" || b:atp_TexOptions =~ "output-format=\s*pdf"
		let ext = ".pdf"
	    else
		let ext = ".dvi"
	    endif
	endif
    endif

    " set the file to print
    let pfile		= ( a:0 == 0 || (a:0 >= 1 && a:1 == "" ) ? b:atp_OutDir . fnamemodify(expand("%"),":t:r") . ext : a:1 )

    " set the printing command
    if a:0 >= 2
	let arg_list	= copy(a:000)
	call remove(arg_list,0)
	let print_options	= " ".join(arg_list, " ")
    else
	let print_options	= ""
    endif

    " print locally or remotely
    " the default is to print locally (g:atp_ssh=`whoami`@localhost)
    let server	= ( exists("g:atp_ssh") ? strpart(g:atp_ssh,stridx(g:atp_ssh,"@")+1) : "localhost" )

    echomsg "[ATP:] server " . server
    echomsg "[ATP:] file   " . pfile

    if server =~ 'localhost'
	let cmd	= g:atp_lprcommand . " " . print_options . " " .  fnameescape(pfile)

	redraw!
	echomsg "[ATP:] printing ...  " . cmd
	call system(cmd)
"     " print over ssh on the server g:atp_ssh with the printer a:1 (or the
    " default system printer if a:0 == 0
    else 
	let cmd="cat " . fnameescape(pfile) . " | ssh " . g:atp_ssh . " " . g:atp_lprcommand . print_options
	call system(cmd)
    endif
endfunction

function! atplib#various#Lpr(...)
    call atplib#outdir()

    " set the extension of the file to print
    " if prining the tex output file.
    if a:0 == 0 || a:0 >= 1 && a:1 == ""
	let ext = get(g:atp_CompilersDict, b:atp_TexCompiler, "not present")
	if ext == "not present"
	    echohl WarningMsg
	    echomsg "[ATP:] ".b:atp_TexCompiler . " is not present in g:atp_CompilersDict"
	    echohl None
	    return "extension not found"
	endif
	if b:atp_TexCompiler =~ "lua"
	    if b:atp_TexOptions == "" || b:atp_TexOptions =~ "output-format=\s*pdf"
		let ext = ".pdf"
	    else
		let ext = ".dvi"
	    endif
	endif
    endif

    " set the file to print
    let pfile		= ( a:0 == 0 || (a:0 >= 1 && a:1 == "" ) ? b:atp_OutDir . fnamemodify(expand("%"),":t:r") . ext : a:1 )
    
    " set the printing command
    if a:0 >= 1
	let arg_list	= copy(a:000)
	let print_options	= " ".join(arg_list, " ")." "
    else
	let print_options	= " "
    endif

    let cmd	= g:atp_lprcommand . print_options . fnameescape(pfile)

    redraw!
    echomsg "[ATP:] printing ...  " . cmd
    call system(cmd)
endfunction
" The command only prints the output file.
fun! atplib#various#Lpstat()
    if exists("g:apt_ssh") 
	let server=strpart(g:atp_ssh,stridx(g:atp_ssh,"@")+1)
    else
	let server='locahost'
    endif
    if server == 'localhost'
	echo system("lpstat -l")
    else
	echo system("ssh " . g:atp_ssh . " lpstat -l ")
    endif
endfunction

" This function is used for completetion of the command SshPrint
function! atplib#various#ListPrinters(A,L,P)
    if exists("g:atp_ssh") && g:atp_ssh !~ '@localhost' && g:atp_ssh != ""
	let cmd="ssh -q " . g:atp_ssh . " lpstat -a | awk '{print $1}'"
    else
	let cmd="lpstat -a | awk '{print $1}'"
    endif
    return system(cmd)
endfunction

function! atplib#various#ListLocalPrinters(A,L,P)
    let cmd="lpstat -a | awk '{print $1}'"
    return system(cmd)
endfunction

" custom style completion
function! atplib#various#Complete_lpr(ArgLead, CmdLine, CPos)
    if a:CmdLine =~ '-[Pd]\s\+\w*$'
	" complete printers
	return atplib#various#ListPrinters(a:ArgLead, "", "")
    elseif a:CmdLine =~ '-o\s\+[^=]*$'
	" complete option
	return join(g:atp_CupsOptions, "\n")
    elseif a:CmdLine =~ '-o\s\+Collate=\%(\w\|-\)*$'
	return join(['Collate=True', 'Collate=False'], "\n")
    elseif a:CmdLine =~ '-o\s\+page-set=\%(\w\|-\)*$'
	return join(['opage-set=odd', 'page-set=even'], "\n")
    elseif a:CmdLine =~ '-o\s\+sides=\%(\w\|-\)*$'
	return join(['sides=two-sided-long-edge', 'sides=two-sided-short-edge', 'sides=one-sided'], "\n")
    elseif a:CmdLine =~ '-o\s\+outputorder=\%(\w\|-\)*$'
	return join(['outputorder=reverse', 'outputorder=normal'], "\n")
    elseif a:CmdLine =~ '-o\s\+page-border=\%(\w\|-\)*$'
	return join(['page-border=double', 'page-border=none', 'page-border=double-thick', 'page-border=single', 'page-border=single-thick'], "\n")
    elseif a:CmdLine =~ '-o\s\+job-sheets=\%(\w\|-\)*$'
	return join(['job-sheets=none', 'job-sheets=classified', 'job-sheets=confidential', 'job-sheets=secret', 'job-sheets=standard', 'job-sheets=topsecret', 'job-sheets=unclassified'], "\n")
    elseif a:CmdLine =~ '-o\s\+number-up-layout=\%(\w\|-\)*$'
	return join(['number-up-layout=btlr', 'number-up-layout=btrl', 'number-up-layout=lrbt', 'number-up-layout=lrtb', 'number-up-layout=rlbt', 'number-up-layout=rltb', 'number-up-layout=tblr', 'number-up-layout=tbrl'], "\n")
    elseif a:CmdLine =~ '-o\s\+position=\%(\w\|-\)*$'
	return join(['position=center', 'position=top', 'position=left', 'position=right', 'position=top-left', 'position=top-right', 
		    \ 'position=bottom', 'position=bottom-left', 'position=bottom-right'], "\n")
    endif
    return ""
endfunction

function! atplib#various#CompleteLocal_lpr(ArgLead, CmdLine, CPos)
    if a:CmdLine =~ '-[Pd]\s\+\w*$'
	" complete printers
	return atplib#various#ListLocalPrinters(a:ArgLead, "", "")
    elseif a:CmdLine =~ '-o\s\+[^=]*$'
	" complete option
	return join(g:atp_CupsOptions, "\n")
    elseif a:CmdLine =~ '-o\s\+Collate=\%(\w\|-\)*$'
	return join(['Collate=True', 'Collate=False'], "\n")
    elseif a:CmdLine =~ '-o\s\+page-set=\%(\w\|-\)*$'
	return join(['opage-set=odd', 'page-set=even'], "\n")
    elseif a:CmdLine =~ '-o\s\+sides=\%(\w\|-\)*$'
	return join(['sides=two-sided-long-edge', 'sides=two-sided-short-edge', 'sides=one-sided'], "\n")
    elseif a:CmdLine =~ '-o\s\+outputorder=\%(\w\|-\)*$'
	return join(['outputorder=reverse', 'outputorder=normal'], "\n")
    elseif a:CmdLine =~ '-o\s\+page-border=\%(\w\|-\)*$'
	return join(['page-border=double', 'page-border=none', 'page-border=double-thick', 'page-border=single', 'page-border=single-thick'], "\n")
    elseif a:CmdLine =~ '-o\s\+job-sheets=\%(\w\|-\)*$'
	return join(['job-sheets=none', 'job-sheets=classified', 'job-sheets=confidential', 'job-sheets=secret', 'job-sheets=standard', 'job-sheets=topsecret', 'job-sheets=unclassified'], "\n")
    elseif a:CmdLine =~ '-o\s\+number-up-layout=\%(\w\|-\)*$'
	return join(['number-up-layout=btlr', 'number-up-layout=btrl', 'number-up-layout=lrbt', 'number-up-layout=lrtb', 'number-up-layout=rlbt', 'number-up-layout=rltb', 'number-up-layout=tblr', 'number-up-layout=tbrl'], "\n")
    elseif a:CmdLine =~ '-o\s\+position=\%(\w\|-\)*$'
	return join(['position=center', 'position=top', 'position=left', 'position=right', 'position=top-left', 'position=top-right', 
		    \ 'position=bottom', 'position=bottom-left', 'position=bottom-right'], "\n")
    endif
    return ""
endfunction
" }}}
" {{{  atplib#various#ReloadATP
" ReloadATP() - reload all the tex_atp functions and delete all autoload functions from
" autoload/atplib.vim
try
function! atplib#various#ReloadATP(bang)
    " First source the option file
    let common_file	= split(globpath(&rtp, 'ftplugin/ATP_files/common.vim'), "\n")[0]
    let options_file	= split(globpath(&rtp, 'ftplugin/ATP_files/options.vim'), "\n")[0]
    let g:atp_reload_functions = ( a:bang == "!" ? 1 : 0 ) 
    if a:bang == ""
	execute "source " . common_file
	execute "source " . options_file 

	" Then source atprc file
	let path = get(split(globpath($HOME, '/.atprc.vim', 1), "\n"), 0, "")
	if filereadable(path) && has("unix")
	    " Note: in $HOME/.atprc file the user can set all the local buffer
	    " variables without using autocommands
	    execute 'source ' . fnameescape(path)
	else
	    let path	= get(split(globpath(&rtp, "**/ftplugin/ATP_files/atprc.vim"), "\n"), 0, "")
	    if path != ""
		execute 'source ' . fnameescape(path)
	    endif
	endif
    else
	" Reload all functions and variables, 
	let tex_atp_file = split(globpath(&rtp, 'ftplugin/tex_atp.vim'), "\n")[0]
	execute "source " . tex_atp_file

	" delete functions from autoload/atplib.vim:
	let atplib_files = join(map(split(globpath(&rtp, 'autoload/atplib.vim')."\n".globpath(&rtp, 'autoload/atplib/*.vim'), "\n"), "fnameescape(v:val)"), " ")
	let saved_loclist = getloclist(0)
	try
	    exe 'silent! lvimgrep /^\s*fun\%[ction]!\=\s\+/gj '.atplib_files
	catch E486:
	endtry
	let list=map(getloclist(0), 'v:val["text"]')
	call setloclist(0,saved_loclist)
	call map(list, 'matchstr(v:val, ''^\s*fun\%[ction]!\=\s\+\zsatplib#\S\+\ze\s*('')')
	for fname in list
	    if fname != "" && fname != "atplib#various#ReloadATP" && fname != "atplib#various#UpdateATP"
		try
		    exe 'delfunction '.fname
		catch /E130:/
		endtry
	    endif
	endfor
    endif
    let g:atp_reload_functions 	= 0
endfunction
catch /E127:/
    " Cannot redefine function, function is in use.
endtry
" }}}
" {{{ atplib#various#Preambule
function! atplib#various#Preamble()
    let loclist = getloclist(0)
    let winview = winsaveview()
    exe '1lvimgrep /^[^%]*\\begin\s*{\s*document\s*}/j ' . fnameescape(b:atp_MainFile)
    let linenr = get(get(getloclist(0), 0, {}), 'lnum', 'nomatch')
    if linenr != 'nomatch'
	if expand("%:p") != atplib#FullPath(b:atp_MainFile)
	    let cfile = expand("%:p")

	    exe "keepalt edit " . b:atp_MainFile 
	endif
	exe "1," . (linenr-1) . "print"
	if exists("cfile")
	    exe "keepalt edit " . cfile
	endif
	call winrestview(winview)
    else	
	echomsg "[ATP:] not found \begin{document}."
    endif
endfunction
" }}}
" {{{ atplib#various#GetAMS
try
function! atplib#various#GetAMSRef(what, bibfile)
    let what = substitute(a:what, '\s\+', ' ',	'g') 
    let what = substitute(what, '%',	'%25',	'g')
    let what = substitute(what, ',',	'%2C',	'g') 
    let what = substitute(what, ':',	'%3A',	'g')
    let what = substitute(what, ';',	'%3B',	'g')
    let what = substitute(what, '/',	'%2F',	'g')
    let what = substitute(what, '?',	'%3F',	'g')
    let what = substitute(what, '+',	'%2B',	'g')
    let what = substitute(what, '=',	'%3D',	'g')
    let what = substitute(what, '#',	'%23',	'g')
    let what = substitute(what, '\$',	'%24',	'g')
    let what = substitute(what, '&',	'%26',	'g')
    let what = substitute(what, '@',	'%40',	'g')
    let what = substitute(what, ' ',	'+',	'g')

 
    " Get data from AMS web site.
    let atpbib_WgetOutputFile = tempname()
    let g:atpbib_WgetOutputFile = atpbib_WgetOutputFile
    let URLquery_path = split(globpath(&rtp, 'ftplugin/ATP_files/url_query.py'), "\n")[0]
    if a:bibfile != "nobibfile"
	let url="http://www.ams.org/mathscinet-mref?ref=".what."&dataType=bibtex"
    else
	let url="http://www.ams.org/mathscinet-mref?ref=".what."&dataType=tex"
    endif
    let cmd=g:atp_Python." ".shellescape(URLquery_path)." ".shellescape(url)." ".shellescape(atpbib_WgetOutputFile)
    call system(cmd)
    let loclist = getloclist(0)

    try
	exe '1lvimgrep /\CNo Unique Match Found/j ' . fnameescape(atpbib_WgetOutputFile)
    catch /E480/
    endtry
    if len(getloclist(0))
	return ['NoUniqueMatch']
    endif

    if len(b:AllBibFiles) > 0
	let pattern = '@\%(article\|book\%(let\)\=\|conference\|inbook\|incollection\|\%(in\)\=proceedings\|manual\|masterthesis\|misc\|phdthesis\|techreport\|unpublished\)\s*{\|^\s*\%(ADDRESS\|ANNOTE\|AUTHOR\|BOOKTITLE\|CHAPTER\|CROSSREF\|EDITION\|EDITOR\|HOWPUBLISHED\|INSTITUTION\|JOURNAL\|KEY\|MONTH\|NOTE\|NUMBER\|ORGANIZATION\|PAGES\|PUBLISHER\|SCHOOL\|SERIES\|TITLE\|TYPE\|VOLUME\|YEAR\|MRCLASS\|MRNUMBER\|MRREVIEWER\)\s*=\s*.*$'
	try 
	    exe 'lvimgrep /'.pattern.'/j ' . fnameescape(atpbib_WgetOutputFile)
	catch /E480:/
	endtry
	let data = getloclist(0)
	call setloclist(0, loclist)

	if !len(data) 
	    echohl WarningMsg
	    echomsg "[ATP:] nothing found."
	    echohl None
	    return [0]
	endif

	let linenumbers = map(copy(data), 'v:val["lnum"]')
	let begin	= min(linenumbers)
	let end	= max(linenumbers)

	let bufnr = bufnr(atpbib_WgetOutputFile)
	" To use getbufline() buffer must be loaded. It is enough to use :buffer
	" command because vimgrep loads buffer and then unloads it. 
	execute "buffer " . bufnr
	let bibdata	= getbufline(bufnr, begin, end)
	execute "bdelete " . bufnr 
	let type = matchstr(bibdata[0], '@\%(article\|book\%(let\)\=\|conference\|inbook\|incollection\|\%(in\)\=proceedings\|manual\|masterthesis\|misc\|phdthesis\|techreport\|unpublished\)\ze\s*\%("\|{\|(\)')
        " Suggest Key:
	let bibkey = input("Provide a key (Enter for the AMS bibkey): ")
	if !empty(bibkey)
	    let bibdata[0] 	= type . '{' . bibkey . ','
	else
	    let bibdata[0] 	= substitute(matchstr(bibdata[0], '@\w*.*$'), '\(@\w*\)\(\s*\)', '\1', '')
	    " This will be only used to echomsg:
	    let bibkey	= matchstr(bibdata[0], '@\w*.\s*\zs[^,]*')
	endif
	call add(bibdata, "}")

	" Open bibfile and append the bibdata:
	execute "silent! edit " . a:bibfile
	if getline(line('$')) !~ '^\s*$' 
	    let bibdata = extend([''], bibdata)
	endif
	call append(line('$'), bibdata)
	normal GG
	echohl WarningMsg
	echomsg "[ATP:] bibkey " . bibkey . " appended to: " . a:bibfile 
	echohl None
    else
	" If the user is using \begin{bibliography} environment.
	let pattern = '^<tr><td align="left">'
	try 
	    exe 'lvimgrep /'.pattern.'/j ' . fnameescape(atpbib_WgetOutputFile)
	catch /E480:/
	endtry
	let data = getloclist(0)
	let g:data = data
	if !len(data) 
	    echohl WarningMsg
	    echomsg "[ATP:] nothing found."
	    echohl None
	    return [0]
	elseif len(data) > 1
	    echoerr "ATP Error: AMSRef vimgrep pattern error. You can send a bug report. Please include the exact :ATPRef command." 
	endif
	let bib_data = data[0]['text']
	let ams_file = readfile(atpbib_WgetOutputFile)
	if bib_data !~ '<\/td><\/tr>'
	    let lnr	= data[0]['lnum']
	    while bib_data !~ '<\/td><\/tr>'
		let lnr+=1
		let line = ams_file[lnr-1]
		echo line
		let bib_data .= line
	    endwhile
	endif
	let g:bib_data = bib_data

	let bibref = '\bibitem{} ' . matchstr(bib_data, '^<tr><td align="left">\zs.*\ze<\/td><\/tr>')
	let g:atp_bibref = bibref
	exe "let @" . g:atp_bibrefRegister . ' = "' . escape(bibref, '\"') . '"'
	let bibdata = [ bibref ]
    endif
    let g:atp_bibdata = bibdata
"     call delete(atpbib_WgetOutputFile)
    return bibdata
endfunction
catch /E127/
endtry "}}}
" {{{ atplib#various#AMSRef
function! atplib#various#AMSRef(bang, what)
    if !exists("b:AllBibFiles")
	call atplib#search#FindInputFiles(b:atp_MainFile)
    endif
    if len(b:AllBibFiles) > 1
	let bibfile = inputlist(extend("Which bib file to use?", b:AllBibFiles))
    elseif len(b:AllBibFiles) == 1
	let bibfile = b:atp_BibFiles[0]
    elseif !len(b:AllBibFiles)
	let bibfile = "nobibfile"
    endif

    let return=atplib#various#GetAMSRef(a:what, bibfile)
    if a:bang == "" && bibfile != "nobibfile" && return != [0] && return != ['NoUniqueMatch']
	silent! w
	silent! bd
    elseif bibfile == "nobibfile" && return != [0] && return != ['NoUniqueMatch']
	redraw
	echohl WarningMsg
	echomsg "[ATP:] found bib data is in register " . g:atp_bibrefRegister
	echohl None
    elseif return[0] == 'NoUniqueMatch' 
	redraw
	echohl WarningMsg
	echomsg "[ATP:] no Unique Match Found"
	echohl None
    endif
endfunction
"}}}
"{{{ atplib#various#Dictionary
function! atplib#various#Dictionary(word)
    redraw
    let URLquery_path 	= split(globpath(&rtp, 'ftplugin/ATP_files/url_query.py'), "\n")[0]
    let url		= "http://www.impan.pl/cgi-bin/dictsearch?q=".a:word
    let wget_file 	= tempname()
    let cmd=g:atp_Python." ".shellescape(URLquery_path)." ".shellescape(url)." ".shellescape(wget_file)
    call system(cmd)
    let loclist		= getloclist(0)
    exe 'silent! lvimgrep /\CMathematical English Usage - a Dictionary/j '.fnameescape(wget_file)
    let entry=get(readfile(wget_file),get(get(getloclist(0),0,{}),'lnum',-1)+1, -1)
    if entry == -1
	call delete(wget_file)
	redraw
	echohl WarningMsg
	echomsg "[ATP:] internet connection seems to be broken."
	echohl Normal
	return
    endif
    call setloclist(0, loclist)
    let entry		= substitute(entry, '<p>', "\n", 'g')
    let entry		= substitute(entry, '<h4>\zs\([0-9]\+\)\ze</h4>', "\n\\1", 'g')
    let entry		= substitute(entry, '<[^>]\+>', '', 'g')
    let entry		= substitute(entry, '\n\zs\([0-9]\+\)\s*\n', '\n\1 ', 'g')
    if &enc == 'utf-8'
	let entry		= substitute(entry, '&#8594;', '→', 'g')
	let entry		= substitute(entry, '&#8734;', '∞', 'g')
	let entry		= substitute(entry, '&lang;', '⟨', 'g')
	let entry		= substitute(entry, '&rang;', '⟩', 'g')
	let entry		= substitute(entry, '&#8805;', '≥', 'g')
	let entry		= substitute(entry, '&#8804;', '≤', 'g')
	let entry		= substitute(entry, '&#8721;\s*', '∑', 'g')
	let entry		= substitute(entry, '&#960;', '⊓', 'g')
    else
	let entry		= substitute(entry, '&#8594;', '->', 'g')
	let entry		= substitute(entry, '&#8734;', '\infty ', 'g')
	let entry		= substitute(entry, '&lang;', '<', 'g')
	let entry		= substitute(entry, '&rang;', '>', 'g')
	let entry		= substitute(entry, '&#8721;\s*', '\sum ', 'g')
    endif
    let entry		= substitute(entry, '&#822[01];', '"', 'g')
    let entry		= substitute(entry, '&nbsp;', ' ', 'g')
    let entry		= substitute(entry, 'Lists of words starting with.*', '', 'g')
    let entry		= substitute(entry, '\.\{4,}', '...', 'g')
    let entry_list	= split(entry, "\n")
    let i=0
    redraw
    for line in entry_list
	if i == 0
	    echoh Title
	elseif line =~ '\[see also:'
	    echohl WarningMsg
	else
	    let line=substitute(line, '^\s*', '', '')
	endif
	echo line
	if line =~ '\[see also:' || i == 0
	    echohl None
	endif
	let i+=1
    endfor
    call delete(wget_file)
endfunction

function! atplib#various#Complete_Dictionary(ArgLead, CmdLine, CursorPos)
    let word_list = [ 'across', 'afford', 'alternative', 'appear',
\ 'ask', 'abbreviate', 'act', 'afield', 'alternatively', 'appearance', 'aspect',
\ 'abbreviation', 'action', 'aforementioned', 'although', 'applicability', 'assert', 'able',
\ 'actual', 'after', 'altogether', 'applicable', 'assertion', 'abound', 'actually',
\ 'again', 'always', 'application', 'assess', 'about', 'adapt', 'against',
\ 'ambiguity', 'apply', 'assign', 'above', 'adaptation', 'agree', 'among',
\ 'appreciation', 'associate', 'absence', 'add', 'agreement', 'amount', 'approach',
\ 'assume', 'absorb', 'addition', 'aid', 'analogous', 'appropriate', 'assumption',
\ 'abstract', 'additional', 'aim', 'analogously', 'appropriately', 'at', 'abundance',
\ 'additionally', 'alas', 'analogue', 'approximate', 'attach', 'abuse', 'address',
\ 'albeit', 'analogy', 'approximately', 'attain', 'accessible', 'adhere', 'algebra',
\ 'analyse', 'arbitrarily', 'attempt', 'accidental', 'ad', 'hoc', 'algorithm',
\ 'analysis', 'arbitrary', 'attention', 'accomplish', 'adjoin', 'all', 'angle',
\ 'area', 'author', 'accord', 'adjust', 'allow', 'announce', 'argue',
\ 'automatic', 'accordance', 'adjustment', 'allude', 'anomalous', 'argument', 'automatically', 'according', 'admit', 
\ 'almost', 'another', 'arise', 'auxiliary', 'accordingly', 'adopt', 'alone', 'answer', 'around', 'available', 'account', 
\ 'advance', 'along', 'any', 'arrange', 'average', 'accurate', 'advantage',
\ 'already', 'apart', 'arrangement', 'avoid', 'achieve', 'advantageous', 'also',
\ 'apparatus', 'arrive', 'await', 'achievement', 'advent', 'alter', 'apparent',
\ 'article', 'aware', 'acknowledge', 'affect', 'alternate', 'apparently', 'artificial',
\ 'away', 'acquire', 'affirmative', 'alternately', 'appeal', 'as', 
\ 'back', 'be', 'behave', 'besides', 'bottom', 
\ 'bring', 'background', 'bear', 'behaviour', 'best', 'bound', 'broad',
\ 'backward(s)', 'because', 'behind', 'better', 'boundary', 'broadly', 'ball',
\ 'become', 'being', 'between', 'bracket', 'build', 'base', 'before',
\ 'believe', 'beware', 'break', 'but', 'basic', 'beforehand', 'belong',
\ 'beyond', 'brevity', 'by', 'basically', 'begin', 'below', 'borrow',
\ 'brief', 'bypass', 'basis', 'beginning', 'benefit', 'both', 'briefly',
\ 'by-product', 'calculate', 'choose', 'commonly', 'concisely', 'constantly',
\ 'convert', 'calculation', 'circle', 'companion', 'conclude', 'constitute', 'convey',
\ 'call', 'circumstances', 'compare', 'conclusion', 
\ 'constraint', 'convince', 'can', 'circumvent', 'comparison', 'concrete', 'construct',
\ 'coordinate', 'cancel', 'cite', 'compensate', 'condition', 'construction', 'core',
\ 'capture', 'claim', 'complement', 'conditional', 'consult', 'corollary', 'cardinality',
\ 'clarity', 'complete', 'conduct', 'contain', 'correct', 'care', 'class',
\ 'completely', 'conference', 'content', 'correspond', 'careful', 'classic', 'completeness',
\ 'confine', 'context', 'correspondence', 'carefully', 'classical', 'completion', 'confirm',
\ 'continue', 'coset', 'carry', 'classification', 'complex', 'conflict', 'continuous',
\ 'cost', 'case', 'clear', 'complicated', 'confound', 'continuum', 'could',
\ 'category', 'clearly', 'complication', 'confuse', 'contradict', 'count', 'cause',
\ 'close', 'compose', 'confusion', 'contradiction', 'counterexample', 'caution', 'closely',
\ 'composition', 'conjecture', 'contrary', 'couple', 'centre', 'clue', 'comprehensive',
\ 'conjunction', 'contrast', 'course', 'certain', 'cluster', 'comprise', 'connect',
\ 'contribute', 'cover', 'certainly', 'coefficient', 'computable', 'connection', 'contribution',
\ 'create', 'challenge', 'coincidence', 'computation', 'consecutive', 'control', 'criterion',
\ 'chance', 
\ 'collect', 'computational', 'consequence', 'convenience', 'critical', 'change', 'collection',
\ 'compute', 'consequently', 'convenient', 'cross', 'character', 'column', 'conceivably',
\ 'consider', 'conveniently', 'crucial', 'characteristic', 'combine', 'concentrate', 'considerable',
\ 'convention', 'crucially', 'characterization', 'come', 'concept', 'considerably', 'converge',
\ 'cumbersome', 'characterize', 'commence', 'conceptually', 'consideration', 'convergence', 'curiously',
\ 'check', 'comment', 'concern', 'consist', 'converse', 'customary', 'choice',
\ 'common', 'concise', 'constant', 'conversely', 'cut', 'data',
\ 'definiteness', 'derive', 'differ', 'discussion', 'dominate', 'date', 'definition',
\ 'describe', 'difference', 'disjoint', 'doomed', 'deal', 'degree', 'description',
\ 'different', 'disparate', 'double', 'decay', 'delete', 'deserve', 'differently',
\ 'dispense', 'doubly', 'decide', 'deliberately', 'design', 'difficult', 'display',
\ 'doubt', 'declare', 'delicate', 'designate', 'difficulty', 'disprove', 'down',
\ 'decline', 'demand', 'desirable', 'digress', 'disregard', 'downward(s)', 'decompose',
\ 'demonstrate', 'desire', 'dimension', 'distance', 'draft', 'decomposition', 'denote',
\ 'detail', 'diminish', 'distinct', 'draw', 'decrease', 'depart', 'deteriorate',
\ 'direct', 'distinction', 'drawback', 'dedicate', 'depend', 'determine', 'direction',
\ 'distinguish', 'drop', 'deduce', 'dependence', 'develop', 'directly', 'distribute',
\ 'due', 'deep', 'dependent', 'development', 'disadvantage', 'distribution', 'duration',
\ 'default', 'depict', 'device', 'disappear', 'divide', 'during', 'defer',
\ 'depth', 'devote', 'discover', 'do', 'define', 'derivation', 'diameter',
\ 'discuss', 'document', 'each', 'embrace', 'entirely', 'establish',
\ 'exception', 'explicit', 'ease', 'emerge', 'entry', 'establishment', 'exceptional',
\ 'explicitly', 'easily', 'emphasis', 'enumerate', 'estimate', 'exercise', 'exploit',
\ 'easy', 'emphasize', 'enumeration', 'estimation', 'exchange', 'exploration', 'effect',
\ 'employ', 'envisage', 'even', 'exclude', 'explore', 'effective', 'enable',
\ 'equal', 'event', 'exclusive', 'expose', 'effectively', 'encircle', 'equality',
\ 'eventual', 'exclusively', 'exposition', 'effectiveness', 'encompass', 'equally', 'eventually',
\ 'exemplify', 'express', 'effort', 'encounter', 'equate', 'ever', 'exhibit',
\ 'expression', 'either', 'encourage', 'equation', 'every', 'exist', 'extend',
\ 'elaborate', 'end', 'equip', 'evidence', 'existence', 'extension', 'elegant',
\ 'enhance', 'equivalent', 'evident', 
\ 'expand', 'extensive', 'element', 'enjoy', 'equivalently', 'evidently', 'expansion',
\ 'extensively', 'elementary', 'enough', 'erroneous', 'exactly', 'expect', 'extent',
\ 'eliminate', 'ensuing', 'error', 'examination', 'expectation', 'extra', 'else',
\ 'ensure', 'especially', 'examine', 'expense', 'extract', 'elsewhere', 'entail',
\ 'essence', 'example', 'explain', 'extreme', 'embed', 'enter', 'essential',
\ 'exceed', 'explanation', 'embedding', 'entire', 'essentially', 'except', 'explication',
\ 'fact', 'fashion', 'finally', 'follow', 'formulation', 'from',
\ 'factor', 'fast', 'find', 'for', 'fortunately', 'fulfil', 'fail',
\ 'feasible', 'fine', 'force', 'forward', 'full', 'fairly', 'feature',
\ 'finish', 'foregoing', 'foundation', 'fully', 'fall', 'fellowship', 'first',
\ 'form', 'fraction', 'furnish', 'fallacious', 'few', 'fit', 'formalism',
\ 'framework', 'further', 'false', 'field', 'fix', 'formally', 'free',
\ 'furthermore', 'familiar', 'figure', 'focus', 'former', 'freedom', 'futile',
\ 'family', 'fill', '-fold', 'formula', 'freely', 'future', 'far',
\ 'final', 'folklore', 'formulate', 'frequently', 'gain', 'generality',
\ 'generate', 'glue', 'grasp', 'ground', 'gap', 'generalization', 'get',
\ 'go', 'grateful', 'grow', 'gather', 'generalize', 'give', 'good',
\ 'gratefully', 'growth', 'general', 'generally', 'glance', 'grant', 'great',
\ 'guarantee', 'half', 'hardly', 'heavy', 'here', 'hinder',
\ 'hospitality', 'hand', 'harm', 'help', 'hereafter', 'hold', 'how',
\ 'handle', 'have', 'helpful', 'heuristic', 'hope', 'however', 'happen',
\ 'heart', 'hence', 'high', 'hopeless', 'hypothesis', 'hard', 'heavily',
\ 'henceforth', 'highly', 'hopelessly', 'idea', 'importance', 'independence',
\ 'informally', 'integrate', 'introduction', 'identical', 'important', 'independent', 'information',
\ 'integration', 'intuition', 'identify', 'impose', 'independently', 'informative', 'intend',
\ 'intuitively', 'identity', 'impossible', 'indeterminate', 'ingredient', 'intention', 'invalid',
\ 'i.e.', 'impracticable', 'indicate', 'inherent', 'intentionally', 'invariant', 'if',
\ 'improve', 'indication', 'initially', 'interchange', 'inverse', 'ignore', 'improvement',
\ 'indistinguishable', 'initiate', 'interchangeably', 'investigate', 'illegitimate', 'impulse', 'individual',
\ 'innermost', 
\ 'interest', 'investigation', 'illuminate', 'in', 'individually', 'inordinately', 'interplay',
\ 'invoke', 'illustrate', 'inability', 'induce', 'insert', 'interpret', 'involve',
\ 'illustration', 'incidentally', 'induction', 'inside', 'interpretation', 'involved', 'image',
\ 'include', 'inductive', 'inspection', 'intersect', 'inward(s)', 'immediate', 'incomparable',
\ 'inductively', 'inspiration', 'intersection', 'irrelevant', 'immediately', 'incompatible', 'inequality',
\ 'inspire', 'interval', 'irrespective', 'implement', 'incomplete', 'infer', 'instead',
\ 'intimately', 'issue', 'implementation', 'increase', 'infinite', 'institution', 'into',
\ 'it', 'implication', 'indebt', 'infinitely', 'integer', 'intricate', 'item',
\ 'implicit', 'indeed', 'infinity', 'integrable', 'intrinsic', 'iterate', 'imply',
\ 'indefinitely', 'influence', 'integral', 'introduce', 'itself', 'job',
\ 'join', 'just', 'justify', 'juxtaposition', 'keep', 'key',
\ 'kind', 'know', 'knowledge', 'label', 'latter', 'lemma',
\ 'lie', 'link', 'lose', 'lack', 'lay', 'lend', 'light',
\ 'list', 'loss', 'language', 'lead', 'length', 'like', 'literature',
\ 'lot', 'large', 'learn', 'lengthy', 'likely', 'little', 'low',
\ 'largely', 'least', 'less', 'likewise', 'locate', 'lower', 'last',
\ 'leave', 'let', 'limit', 'location', 'lastly', 'left', 'letter',
\ 'limitation', 'long', 'late', 'legitimate', 'level', 'line', 'look',
\ 'machinery', 'many', 'meaningful', 'middle', 'model', 'most',
\ 'magnitude', 'map', 'meaningless', 'might', 'moderate', '-most', 'main',
\ 'mark', 'means', 'mild', 'modification', 'mostly', 'mainly', 'match',
\ 'measure', 'mimic', 'modify', 'motivate', 'maintain', 'material', 'meet',
\ 'mind', 'modulus', 'motivation', 'major', 'matrix', 'member', 'minimal',
\ 'moment', 'move', 'majority', 'matter', 'membership', 'minimum', 'monotone',
\ 'much', 'make', 'maximal', 'mention', 'minor', 'more', 'multiple',
\ 'manage', 'maximum', 'mere', 'minus', 'moreover', 'multiplication', 'manifestly',
\ 'may', 'merely', 'miss', '-morphic', 'multiply', 'manipulate', 'mean',
\ 'merit', 'mistake', '-morphically', 'must', 'manner', 'meaning', 'method',
\ 'mnemonic', '-morphism', 
\ 'mutatis', 'mutandis', 'name', 'nearby', 'need', 'next',
\ 'norm', 'notice', 'namely', 'nearly', 'negative', 'nice', 'normally',
\ 'notion', 'narrowly', 'neat', 'neglect', 'nicety', 'not', 'novelty',
\ 'natural', 'necessarily', 'negligible', 'no', 'notably', 'now', 'naturally',
\ 'necessary', 'neither', 'non-', 'notation', 'nowhere', 'nature', 'necessitate',
\ 'never', 'none', 'note', 'number', 'near', 'necessity', 'nevertheless',
\ 'nor', 'nothing', 'numerous', 'obey', 'occasion', 'omission',
\ 'opposite', 'ought', 'overall', 'object', 'occasionally', 'omit', 'or',
\ 'out', 'overcome', 'objective', 'occur', 'on', 'order', 'outcome',
\ 'overlap', 'obscure', 'occurrence', 'once', 'organization', 'outline', 'overlook',
\ 'observation', 'odds', 'one', 'organize', 'outnumber', 'overview', 'observe',
\ 'of', 'only', 'origin', 'output', 'owe', 'obstacle', 'off',
\ 'onwards', 'original', 'outset', 'own', 'obstruction', 'offer', 'open',
\ 'originally', 'outside', 'obtain', 'offset', 'operate', 'originate', 'outstanding',
\ 'obvious', 'often', 'opportunity', 'other', 'outward(s)', 'obviously', 'old',
\ 'oppose', 'otherwise', 'over', 'page', 'penultimate', 'plain',
\ 'preassign', 'previous', 'project', 
\ 'pair', 'percent', 'plausible', 'precede', 'previously', 'promise', 'paper',
\ 'percentage', 'play', 'precise', 'price', 'prompt', 'paragraph', 'perform',
\ 'plentiful', 'precisely', 'primarily', 'proof', 'parallel', 'perhaps', 'plug',
\ 'precision', 'primary', 'proper', 'parameter', 'period', 'plus', 'preclude',
\ 'prime', 'properly', 'parametrize', 'periodic', 'point', 'predict', 'principal',
\ 'property', 'paraphrase', 'permission', 'pose', 'predictable', 'prior', 'proportion',
\ 'parenthesis', 'permit', 'position', 'prefer', 'probability', 'propose', 'part',
\ 'permute', 'positive', 'preferable', 'probably', 'proposition', 'partial', 'persist',
\ 'positively', 'preliminary', 'problem', 'prove', 'partially', 'perspective', 'possession',
\ 'preparatory', 'procedure', 'provide', 'particular', 'pertain', 'possibility', 'prerequisite',
\ 'proceed', 'provided', 'particularly', 'pertinent', 'possible', 'prescribe', 'process',
\ 'provisional', 'partition', 'phenomenon', 'possibly', 'presence', 'produce', 'publish',
\ 'pass', 'phrase', 'postpone', 'present', 'product', 'purpose', 'passage',
\ 'pick', 'potential', 'presentation', 'professor', 'pursue', 'path', 'picture',
\ 'power', 'preserve', 'profound', 'push', 'pattern', 'piece', 'practically',
\ 'presume', 'profusion', 'put', 'peculiar', 'place', 'practice', 'prevent',
\ 'progress', 'quality', 'quantity', 'quickly', 'quote', 'quantitative',
\ 'question', 'quite', 'radius', 'rearrangement', 'referee', 'remainder',
\ 'requirement', 'reverse', 'raise', 'reason', 'reference', 'remark', 'requisite',
\ 'revert', 'random', 'reasonable', 'refine', 'remarkable', 'research', 'review',
\ 'range', 'reasonably', 'refinement', 'remarkably', 'resemblance', 'revise',
\ 'rank', 'reasoning', 'reflect', 'remedy', 
\ 'resemble', 'revolution', 'rapidly', 'reassemble', 'reflection', 'remember', 'reserve',
\ 'rewrite', 'rare', 'recall', 'reformulate', 'remind', 'resistant', 'right',
\ 'rarely', 'receive', 'reformulation', 'reminiscent', 'resolve', 'rigorous', 'rarity',
\ 'recent', 'refute', 'removal', 'respect', 'rise', 'rate', 'recently',
\ 'regard', 'remove', 'respective', 'role', 'rather', 
\ 'recognition', 'regardless', 'rename', 'respectively', 'root', 'ratio', 'recognize',
\ 'relabel', 'renewal', 'rest', 'rotate', 'reach', 'recommend', 'relate',
\ 'repeat', 'restate', 'rotation', 'read', 'record', 'relation', 'repeatedly',
\ 'restraint', 'rough', 'readability', 'recourse', 'relationship', 'repetition', 'restrict',
\ 'roughly', 'readable', 'recover', 'relative', 'rephrase', 'restriction', 'round',
\ 'reader', 'recur', 'relax', 'replace', 'restrictive', 'routine', 'readily',
\ 'rederive', 'relevance', 'replacement', 'result', 'routinely', 'ready', 'reduce',
\ 'relevant', 'report', 'retain', 'rudimentary', 'realize', 'reduction', 'reliance',
\ 'represent', 'retrieve', 'rule', 'really', 'redundant', 'rely', 'representative',
\ 'return', 'run', 'rearrange', 'refer', 'remain', 'require', 'reveal',
\ 'sequence', 'simplicity', 'specify', 'study', 'suggest',
\ 'sacrifice', 'serious', 'simplify', 'spirit', 'subdivide', 'suggestion', 'sake',
\ 'serve', 'simply', 'split', 'subject', 'suit', 'same', 'set',
\ 'simultaneously', 'square', 'subordinate', 'suitable', 'satisfactory', 'setting', 'since',
\ 'stage', 'subscript', 'suitably', 'satisfy', 'settle', 'single', 'stand',
\ 'subsequence', 'sum', 'save', 'set-up', 'situation', 'standard', 'subsequent',
\ 'summarize', 'say', 'several', 'size', 'standpoint', 'subsequently', 'summary',
\ 'scale', 'shape', 'sketch', 'start', 'substance', 'superfluous', 'scenario',
\ 'share', 'slant', 'state', 'substantial', 'superior', 'scheme', 'sharp',
\ 'slight', 'statement', 'substantially', 'supply', 'scope', 'sharpen', 'slightly',
\ 'stay', 'substantiate', 'support', 'scrutiny', 'shed', 'small', 'step',
\ 'substitute', 'suppose', 'search', 'short', 'so', 'stick', 'subsume',
\ 'suppress', 'second', 'shortcoming', 'solely', 'still', 'subterfuge', 'supremum',
\ 'section', 'shorthand', 'solution', 'stipulation', 'subtle', 'sure', 'see',
\ 'shortly', 'solve', 'straight', 'subtlety', 'surely', 'seek', 'should',
\ 'some', 'straightforward', 'subtract', 'surpass', 'seem', 'show', 'something',
\ 'strange', 'succeed', 'surprise', 'seemingly', 'shrink', 'sometimes', 'strategy',
\ 'success', 'surprisingly', 'segment', 'side', 'somewhat', 'strength', 'successful',
\ 'survey', 'select', 'sight', 'soon', 'strengthen', 'successfully', 'suspect',
\ 'selection', 'sign', 'sophisticated', 'stress', 'successive', 'symbol', 'self-contained',
\ 'significance', 'sort', 'strict', 'successively', 'symmetry', 'self-evident', 'significant',
\ 'source', 'strictly', 'succinct', 'system', 'send', 'significantly', 'space',
\ 'strike', 'succinctly', 'systematic', 'sense', 'signify', 'speak', 'stringent',
\ 'such', 'systematically', 'sensitive', 'similar', 'special', 'strive', 'suffice',
\ 'separate', 'similarity', 'specialize', 'stroke', 'sufficiency', 'separately', 'similarly',
\ 'specific', 'strong', 'sufficient', 'sequel', 'simple', 'specifically', 
\ 'structure', 'sufficiently', 'table', 'tempt', 'theorem', 'three',
\ 'towards', 'truncate', 'tabulate', 'tend', 'theory', 'through', 'tractable',
\ 'truth', 'tacit', 'tentative', 'there', 'throughout', 'transfer', 'try',
\ 'tacitly', 'term', 'thereafter', 'thus', 'transform', 'turn', 'take',
\ 'terminate', 'thereby', 'tie', 'transition', 'twice', 'talk', 'terminology',
\ 'therefore', 'tilde', 'translate', 'two', 'task', 'test', 'these',
\ 'time', 'treat', 'twofold', 'technical', 'text', 'thesis', 'to',
\ 'treatment', 'two-thirds', 'technicality', 'than', 'thing', 'together', 'trial',
\ 'type', 'technique', 'thank', 'think', 'too', 'trick', 'typical',
\ 'technology', 'thanks', 'third', 'tool', 'trivial', 'typically', 'tedious',
\ 'that', 'this', 'top', 'triviality', 'tell', 'the', 'thorough',
\ 'topic', 'trivially', 'temporarily', 'theme', 'those', 'total', 'trouble',
\ 'temporary', 'then', 'though', 'touch', 'true', 'ultimate',
\ 'underlie', 'uniformly', 'unity', 'unresolved', 'useful', 'unaffected', 'underline',
\ 'unify', 'university', 'until', 'usefulness', 'unaware', 'understand', 'unimportant',
\ 'unless', 'unusual', 'usual', 'unchanged', 'undertake', 'union', 'unlike',
\ 'up', 'usually', 'unclear', 'undesirable', 'unique', 'unlikely', 'upon',
\ 'utility', 'under', 'unfortunately', 'uniquely', 'unnecessarily', 'upper', 'utilize',
\ 'undergo', 'uniform', 'unit', 'unnecessary', 'use', 'vacuous',
\ 'valuable', 'variation', 'verification', 'view', 'vacuously', 'value', 'variety',
\ 'verify', 'viewpoint', 'valid', 'vanish', 'various', 'version', 'violate',
\ 'validate', 'variable', 'variously', 'very', 'visit', 'validity', 'variant',
\ 'vary', 'via', 'visualize', 'want', 'well', 'whenever',
\ 'while', '-wise', 'word', 'warrant', 'were', 'where', 'whole',
\ 'wish', 'work', 'way', 'what', 'whereas', 'wholly', 'with',
\ 'worth', 'weak', 'whatever', 'wherever', 'whose', 'within', 'would',
\ 'weaken', 'whatsoever', 'whether', 'why', 'without', 'write', 'weakness',
\ 'when', 'which', 'wide', 'witness', 'wealth', 'whence', 'whichever',
\ 'widely', 'wonder', 'year', 'yet', 'yield', 'zero']
    return join(word_list, "\n")
endfunction

function! atplib#various#MakeListOfWords()
    echo "[ATP:] This takes a while ..."
    let word_list 	= []
    let loclist		= getloclist(0)
    let wget_file 	= tempname()
    let URLquery_path 	= split(globpath(&rtp, 'ftplugin/ATP_files/url_query.py'), "\n")[0]

    for letter in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k' , 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x' , 'y', 'z' ]
	let url		= "http://www.impan.pl/Dictionary/".letter.".html"
	let cmd=g:atp_Python." ".shellescape(URLquery_path)." ".shellescape(url)." ".shellescape(wget_file)
	call system(cmd)
	exe 'lvimgrep /\%(Mathematical English Usage - a Dictionary\|Go to the list of words starting with\)/j '.wget_file
	let file 	= []
	let file_wget 	= readfile(wget_file)
	for i in range((getloclist(0)[0]['lnum']+2),(getloclist(0)[1]['lnum'])-2)
	    call add(file, file_wget[i])
	endfor
	call map(file, 'substitute(v:val, ''<[^>]\+>'', " ", "g")')
	for line in file
	    call extend(word_list, split(line, '\s\+'))
	endfor

    endfor

    let g:word_list		= word_list
    return word_list
endfunction
"}}}
" {{{ atplib#various#WordCount()
function! atplib#various#WordCount(bang, range)

    " if range is current line, count whole project, other wise count the
    " given part of the text (this is the default range for the commmand.
    " range is [ <line1>, <line2> ]

    call atplib#write("nobackup")

    let g:atp_WordCount = {}

    if a:bang == "!"
	for file in keys(filter(copy(b:TypeDict), 'v:val == ''input'''))+[b:atp_MainFile]
	    let wcount = substitute(system("detex -n " . fnameescape(atplib#FullPath(file)) . " | wc -w "), '\D', '', 'g')
	    call extend(g:atp_WordCount, { file : wcount })
	endfor
	let temp 	= tempname()
	let bufnr 	= bufnr("%")
	let winview	= winsaveview()
	if expand("%:p") != atplib#FullPath(b:atp_MainFile)
	    keepalt silent! "edit ".fnameescape(atplib#FullPath(b:atp_MainFile))
	endif
	keepalt silent! "saveas ".temp
	" Delete the preambule
	if &l:filetype == "tex"
	    0
	    let preambule	= search('\\begin{\s*document\s*', 'n')
	    exe '"_d'.preambule.'j'
	endif
	let wcount = substitute(system("detex -n " . fnameescape(fnamemodify(bufname("%"), ":p")) . " | wc -w "), '\D', '', 'g')
	silent! exe "b ".bufnr
	keepjumps call winrestview(winview)
	call extend(g:atp_WordCount, { expand("%") : wcount } )
    elseif a:range == [ string(line(".")), string(line(".")) ] 
	let temp 	= tempname()
	let bufnr 	= bufnr("%")
	let winview	= winsaveview()
	keepalt silent! "saveas ".temp
	" Delete the preambule
	if &l:filetype == "tex"
	    0
	    let preambule	= search('\\begin{\s*document\s*', 'n')
	    exe '"_d'.preambule.'j'
	endif
	let wcount = substitute(system("detex -n " . fnameescape(fnamemodify(bufname("%"), ":p")) . " | wc -w "), '\D', '', 'g')
	silent! exe "b ".bufnr
	keepjumps call winrestview(winview)
	call extend(g:atp_WordCount, { expand("%") : wcount } )
    else
	let temp 	= tempname()
	let range 	= getbufline(bufnr("%"), a:range[0], a:range[1])
	let bufnr 	= bufnr("%")
	let winview	= winsaveview()
	keepalt silent! exe "edit ".temp
	call append(0,range)
	silent! update
	let wcount = substitute(system("detex -n " . fnameescape(fnamemodify(bufname("%"), ":p")) . " | wc -w "), '\D', '', 'g')
	silent! exe "b ".bufnr
	keepjumps call winrestview(winview)
	call extend(g:atp_WordCount, { expand("%") : wcount } )
    endif


    " sum values
    let val = values(g:atp_WordCount)
    let wc_sum = 0
    for i in val
	let wc_sum += i
    endfor

    return wc_sum
endfunction "}}}
" {{{ atplib#various#ShowWordCount()
function! atplib#various#ShowWordCount(bang,range)

    let wc = atplib#various#WordCount(a:bang,a:range)
    let c = 0
    if a:bang == "!" && a:range != [ line("."), line(".") ] 
	echo g:atp_WordCount[b:atp_MainFile] . "\t" . b:atp_MainFile
	for file in b:ListOfFiles
	    if get(g:atp_WordCount, file, "NOFILE") != "NOFILE"
		let c=1
		echo g:atp_WordCount[file] . "\t" . file 
	    endif
	endfor
	if c
	    echomsg wc
	endif
    else
	if a:range == [ line("."), line(".") ] 
	    echomsg wc . "  " . b:atp_MainFile
	else
	    echomsg wc
	endif
    endif
endfunction "}}}
" {{{ atplib#various#Wdiff
" Needs wdiff program.
function! atplib#various#Wdiff(new_file, old_file)

    if !executable("wdiff")
	echohl WarningMsg
	echo "You need to install GNU wdiff program." 
	echohl None
	return 1
    endif

    " Operate on temporary copies:
    try
	let new_file	= readfile(a:new_file)
    catch /E484/
	echohl ErrorMsg
	echomsg "[ATP:] can't open file " . a:new_file
	echohl None
	return 1
    endtry
    try
	let old_file	= readfile(a:old_file)
    catch /E484/
	echohl ErrorMsg
	echomsg "[ATP:] can't open file " . a:old_file
	echohl None
	return 1
    endtry

    " Remove the preamble:
    let new_pend=0
    for line in new_file
	if line =~ '^[^%]*\\begin{document}'
	    break
	endif
	let new_pend+=1
    endfor
    let old_pend=0
    for line in new_file
	if line =~ '^[^%]*\\begin{document}'
	    break
	endif
	let old_pend+=1
    endfor

    let new_preamble	= remove(new_file, 0, new_pend)  
    let old_preamble	= remove(old_file, 0, old_pend)  

"     let g:new_preamble = new_preamble
"     let g:old_preamble = old_preamble
"     let g:new_file	= new_file
"     let g:old_file	= old_file

    let new_tmp		= tempname()
    let old_tmp		= tempname()

    if new_preamble != old_preamble
	let which_pre=inputlist(["Wich preamble to use:", "(1) from " . a:new_file, "(2) from " . a:old_file])
	if which_pre != 1 && which_pre != 2
	    return 0
	endif
    else
	let which_pre = 1
    endif

    execute "keepalt edit " . new_tmp
    call append(0, new_file)
    let buf_new	= bufnr("%")
    "delete all comments
    if expand("%:p") == new_tmp
	silent! execute ':%g/^\s*%/d'
	silent! execute ':%s/\s*\\\@!%.*$//g'
	silent! write
	silent! bdelete
    else
	return 1
    endif

    execute "keepalt edit " . old_tmp
    call append(0, old_file)
    let buf_old	= bufnr("%")
    "delete all comments
    if expand("%:p") == old_tmp
	silent! execute ':%g/^\s*%/d'
	silent! execute ':%s/\s*\\\@!%.*$//g'
	silent! write
	silent! bdelete
    else
	return 1
    endif

    " make wdiff:
    if filereadable("/tmp/wdiff.tex")
	call delete("/tmp/wdiff.tex")
    endif
"     call system("wdiff -w '{\\textcolor{red}{=}' -x '\\textcolor{red}{=}}' -y '{\\textcolor{blue}{+}' -z '\\textcolor{blue}{+}}' " . new_tmp . " " . old_tmp . " > /tmp/wdiff.tex")
    call system("wdiff " . "-w '\\{=' -x '=\\}' -y '\\{+' -z '+\\}'" . " " . new_tmp . " " . old_tmp . " > /tmp/wdiff.tex")
    split /tmp/wdiff.tex

    " Set atp
    let b:atp_autex=0
    let b:atp_ProjectScript=0

    " These do not match multiline changes!
    let s:atp_IDdelete	= matchadd('DiffDelete', '\\{=\zs\%(=\\}\@!\|=\\\@!}\|=\@!\\}\|[^}=\\]\|=\\\@!\|\\}\@!\|=\@<!\\\|\\}\@!\|\\\@<!}\)*\ze=\\}', 10)
    let s:atp_IDadd	= matchadd('DiffAdd', '\\{+\zs\%(+\\}\@!\|+\\\@!}\|+\@!\\}\|[^}+\\]\|+\\\@!\|\\}\@!\|+\@<!\\\|\\}\@!\|\\\@<!}\)*\ze+\\}', 10)
    normal "gg"
    call append(0, ( which_pre == 1 ? new_preamble : old_preamble )) 
    silent! call search('\\begin{document}')
    normal "zt"
    map ]s /\\{[=+]\_.*[+=]\\}<CR>
    map [s ?\\{[=+]\_.*[+=]\\}<CR>
    command! -buffer NiceDiff :call atplib#various#NiceDiff()
endfunction
function! atplib#various#NiceDiff()
    let saved_pos=getpos(".")
    keepjumps %s/\\{=\(\%(=\\}\@!\|=\\\@!}\|=\@!\\}\|[^}=\\]\|=\\\@!\|\\}\@!\|=\@<!\\\|\\}\@!\|\\\@<!}\)*\)=\\}/\\textcolor{red}{\1}/g
    keepjumps %s/\\{+\(\%(+\\}\@!\|+\\\@!}\|+\@!\\}\|[^}+\\]\|+\\\@!\|\\}\@!\|+\@<!\\\|\\}\@!\|\\\@<!}\)*\)+\\}/\\textcolor{blue}{\1}/g
    call cursor(saved_pos[1], saved_pos[2])
    map ]s /\\textcolor{\%(blue\|red\)}{/e+1
    map [s ?\\textcolor{\%(blue\|red\)}{?e+1
    call matchadd('DiffDelete', '\textcolor{red}{[^}]*}', 10)
    call matchadd('DiffAdd', '\textcolor{blue}{[^}]*}',  10)
endfunction "}}}
"{{{ atplib#various#UpdateATP
try 
function! atplib#various#UpdateATP(bang)

	if exists("g:atp_debugUpdateATP") && g:atp_debugUpdateATP
	    exe "redir! > ".g:atp_TempDir."/UpdateATP.log"
	endif
	let s:ext = "tar.gz"
	if a:bang == "!"
	    echo "[ATP:] getting list of available snapshots ..."
	else
	    echo "[ATP:] getting list of available versions ..."
	endif
	let s:URLquery_path = split(globpath(&rtp, 'ftplugin/ATP_files/url_query.py'), "\n")[0]    

	if a:bang == "!"
	    let url = "http://sourceforge.net/projects/atp-vim/files/snapshots/"
	else
	    let url = "http://sourceforge.net/projects/atp-vim/files/releases/"
	endif
	let url_tempname=tempname()."_ATP.html"
	if !exists("g:atp_Python")
	    if has("win32") || has("win64")
		let g:atp_Python = "pythonw.exe"
	    else
		let g:atp_Python = "python"
	    endif
	endif
	let cmd=g:atp_Python." ".s:URLquery_path." ".shellescape(url)." ".shellescape(url_tempname)
	if exists("g:atp_debugUpdateATP") && g:atp_debugUpdateATP
	    let g:cmd=cmd
	    silent echo "url_tempname=".url_tempname
	    silent echo "cmd=".cmd
	endif
	call system(cmd)

	let saved_loclist = getloclist(0)
	exe 'lvimgrep /\C<a\s\+href=".*AutomaticTexPlugin_\d\+\%(\.\d\+\)*\.'.escape(s:ext, '.').'/jg '.url_tempname
	call delete(url_tempname)
	let list = map(getloclist(0), 'v:val["text"]')
	if exists("g:atp_debugUpdateATP") && g:atp_debugUpdateATP
	    silent echo "list=".string(list)
	endif
	if a:bang == "!"
	    call filter(list, 'v:val =~ ''\.tar\.gz\.\d\+-\d\+-\d\+_\d\+-\d\+''')
	endif
	call map(list, 'matchstr(v:val, ''<a\s\+href="\zshttp[^"]*download\ze"'')')
	call setloclist(0,saved_loclist)
	call filter(list, "v:val != ''")
	if exists("g:atp_debugUpdateATP") && g:atp_debugUpdateATP
	    silent echo "atp_versionlist=".string(list)
	endif

	if !len(list)
	    echoerr "No snapshot is available." 
	    if g:atp_debugUpdateATP
		redir END
	    endif
	    return
	endif
	let dict = {}
	for item in list
	    if a:bang == "!"
		let key = matchstr(item, 'AutomaticTexPlugin_\d\+\%(\.\d\+\)*\.tar\.gz\.\zs[\-0-9_]\+\ze')
		if key == ''
		    let key = "00-00-00_00-00"
		endif
		call extend(dict, { key : item})
	    else
		call extend(dict, { matchstr(item, 'AutomaticTexPlugin_\zs\d\+\%(\.\d\+\)*\ze\.tar.gz') : item})
	    endif
	endfor
	if a:bang == "!"
	    let sorted_list = sort(keys(dict), "atplib#various#CompareStamps")
	else
	    let sorted_list = sort(keys(dict), "atplib#various#CompareVersions")
	endif
	if exists("g:atp_debugUpdateATP") && g:atp_debugUpdateATP
	    let g:sorted_list 	= sorted_list
	    let g:dict		= dict
	    silent echo "dict=".string(dict)
	    silent echo "sorted_list=".string(sorted_list)
	endif
	"NOTE: this list might contain one item two times (I'm not filtering well the
	" html sourcefore web page, but this is faster)

	let dir = fnamemodify(split(globpath(&rtp, "ftplugin/tex_atp.vim"), "\n")[0], ":h:h")
	if dir == ""
	    echoerr "[ATP:] Cannot find local ATP directory."
	    if exists("g:atp_debugUpdateATP") && g:atp_debugUpdateATP
		redir END
	    endif
	    return
	endif

	" Stamp of the local version
	let saved_loclist = getloclist(0)
	if a:bang == "!"
	    try
		exe '1lvimgrep /\C^"\s*Time\s\+Stamp:/gj '. split(globpath(&rtp, "ftplugin/tex_atp.vim"), "\n")[0]
		let old_stamp = get(getloclist(0),0, {'text' : '00-00-00_00-00'})['text']
		call setloclist(0, saved_loclist) 
		let old_stamp=matchstr(old_stamp, '^"\s*Time\s\+Stamp:\s*\zs\%(\d\|_\|-\)*\ze')
	    catch /E480:/
		let old_stamp="00-00-00_00-00"
	    endtry
	else
	    try
		exe '1lvimgrep /(ver\.\=\%[sion]\s\+\d\+\%(\.\d\+\)*\s*)/gj ' . split(globpath(&rtp, "doc/automatic-tex-plugin.txt"), "\n")[0]
		let old_stamp = get(getloclist(0),0, {'text' : '00-00-00_00-00'})['text']
		call setloclist(0, saved_loclist) 
		let old_stamp=matchstr(old_stamp, '(ver\.\=\%[sion]\s\+\zs\d\+\%(\.\d\+\)*\ze')
	    catch /E480:/
		let old_stamp="0.0"
	    endtry
	endif
	if exists("g:atp_debugUpdateATP") && g:atp_debugUpdateATP
	    let g:old_stamp	= old_stamp
	    silent echo "old_stamp=".old_stamp
	endif


	let new_stamp = sorted_list[0]
	if exists("g:atp_debugUpdateATP") && g:atp_debugUpdateATP
	    let g:new_stamp	= new_stamp
	    silent echo "new_stamp=".new_stamp
	endif
	 
	"Compare stamps:
	" stamp format day-month-year_hour-minute
	" if o_stamp is >= than n_stamp  ==> return
	let l:return = 1
	if a:bang == "!"
	    let compare = atplib#various#CompareStamps(new_stamp, old_stamp)
	else
	    let compare = atplib#various#CompareVersions(new_stamp, old_stamp) 
	endif
	if exists("g:atp_debugUpdateATP") && g:atp_debugUpdateATP
	    let g:compare	= compare
	endif
	if a:bang == "!"
	    if  compare == 1 || compare == 0
		redraw
		echomsg "You have the latest UNSTABLE version of ATP."
		if exists("g:atp_debugUpdateATP") && g:atp_debugUpdateATP
		    redir END
		endif
		return
	    endif
	else
	    if compare == 1
		redraw
		let l:return = input("You have UNSTABLE version of ATP.\nDo you want to DOWNGRADE to the last STABLE release? type yes/no [or y/n] and hit <Enter> ")
		let l:return = (l:return !~? '^\s*y\%[es]\s*$')
		if l:return
		    call delete(s:atp_tempname)
		    redraw
		    if exists("g:atp_debugUpdateATP") && g:atp_debugUpdateATP
			redir END
		    endif
		    return
		endif
	    elseif compare == 0
		redraw
		echomsg "You have the latest STABLE version of ATP."
		if exists("g:atp_debugUpdateATP") && g:atp_debugUpdateATP
		    redir END
		endif
		return
	    endif
	endif

	redraw
	call  atplib#various#GetLatestSnapshot(a:bang, dict[sorted_list[0]])
	echo "[ATP:] installing ..." 
	call atplib#various#Tar(s:atp_tempname, dir)
	call delete(s:atp_tempname)

	exe "helptags " . finddir("doc", dir)
	ReloadATP
	redraw!
	if a:bang == "!"
	    echomsg "[ATP:] updated to version ".s:ATPversion." (snapshot date stamp ".new_stamp.")." 
	    echo "See ':help atp-news' for changes!"
	else
	    echomsg "[ATP:] ".(l:return ? 'updated' : 'downgraded')." to release ".s:ATPversion
	endif
	if bufloaded(split(globpath(&rtp, "doc/automatic-tex-plugin.txt"), "\n")[0]) ||
		    \ bufloaded(split(globpath(&rtp, "doc/bibtex_atp.txt"), "\n")[0])
	    echo "[ATP:] to reload the ATP help files (and see what's new!), close and reopen them."
	endif
endfunction 
catch E127:
endtry
function! atplib#various#GetLatestSnapshot(bang,url)
    " Get latest snapshot/version
    let url = a:url

    let s:ATPversion = matchstr(url, 'AutomaticTexPlugin_\zs\d\+\%(\.\d\+\)*\ze\.'.escape(s:ext, '.'))
    if a:bang == "!"
	let ATPdate = matchstr(url, 'AutomaticTexPlugin_\d\+\%(\.\d\+\)*.'.escape(s:ext, '.').'.\zs[0-9-_]*\ze')
    else
	let ATPdate = ""
    endif
    let s:atp_tempname = tempname()."_ATP.tar.gz"
    if exists("g:atp_debugUpdateATP") && g:atp_debugUpdateATP
	silent echo "tempname=".s:atp_tempname
    endif
    if !exists("g:atp_Python")
	if has("win32") || has("win64")
	    let g:atp_Python = "pythonw.exe"
	else
	    let g:atp_Python = "python"
	endif
    endif
    let cmd=g:atp_Python." ".shellescape(s:URLquery_path)." ".shellescape(url)." ".shellescape(s:atp_tempname)
    if a:bang == "!"
	echo "[ATP:] getting latest snapshot (unstable version) ..."
    else
	echo "[ATP:] getting latest stable version ..."
    endif
    if exists("g:atp_debugUpdateATP") && g:atp_debugUpdateATP
	silent echo "cmd=".cmd
    endif
    call system(cmd)
endfunction
function! atplib#various#CompareStamps(new, old)
    " newer stamp is smaller 
    " vim sort() function puts smaller items first.
    " new > old => -1
    " new = old => 0
    " new < old => 1
    let new_r=split(a:new, '\%(-\|_\)')
    let old_r=split(a:old, '\%(-\|_\)')
    let new	= [ new_r[2], new_r[1], new_r[0], new_r[3], new_r[4] ]
    let old	= [ old_r[2], old_r[1], old_r[0], old_r[3], old_r[4] ]
    let compare = []
    for i in range(max([len(new), len(old)]))
	let nr = (str2nr(get(new,i,0)) < str2nr(get(old,i,0)) ? 1 : ( str2nr(get(new,i,0)) == str2nr(get(old,i,0)) ? 0 : 2 ))
	call add(compare, nr)
    endfor
    let comp = join(compare, "")
    " comp =~ '^0*1' new is older version 
    return ( comp == 0 ? 0 : ( comp =~ '^0*1' ? 1 : -1 ))
endfunction
function! atplib#various#CompareVersions(new, old)
    " newer stamp is smaller 
    " vim sort() function puts smaller items first.
    " new > old => -1
    " new = old => 0
    " new < old => 1
    let new=split(a:new, '\.')
    let old=split(a:old, '\.')
    let compare = []
    for i in range(max([len(new), len(old)]))
	let nr = (str2nr(get(new,i,0)) < str2nr(get(old,i,0)) ? 1 : ( str2nr(get(new,i,0)) == str2nr(get(old,i,0)) ? 0 : 2 ))
	call add(compare, nr)
    endfor
    let comp = join(compare, "")
    " comp =~ '^0*1' new is older version 
    return ( comp == 0 ? 0 : ( comp =~ '^0*1' ? 1 : -1 ))
endfunction
function! atplib#various#GetTimeStamp(file)
python << END
import vim, tarfile, re

file_name	=vim.eval('a:file')
tar_file	=tarfile.open(file_name, 'r:gz')
def tex(name):
    if re.search('ftplugin/tex_atp\.vim', str(name)):
	return True
    else:
	return False
member=filter(tex, tar_file.getmembers())[0]
pfile=tar_file.extractfile(member)
stamp=""
for line in pfile.readlines():
    if re.match('\s*"\s+Time\s+Stamp:\s+', line):
	stamp=line
	break
try:
    match=re.match('\s*"\s+Time\s+Stamp:\s+([0-9\-_]*)', stamp)
    stamp=match.group(1)
except AttributeError:
    stamp="00-00-00_00-00"
vim.command("let g:atp_stamp='"+stamp+"'")
END
endfunction
function! atplib#various#Tar(file,path)
python << END
import tarfile, vim
file_n=vim.eval("a:file")
path=vim.eval("a:path")
file_o=tarfile.open(file_n, "r:gz")
file_o.extractall(path)
END
endfunction
function! atplib#various#ATPversion()
    " This function is used in opitons.vim
    let saved_loclist = getloclist(0)
    try
	exe 'lvimgrep /\C^"\s*Time\s\+Stamp:/gj '. split(globpath(&rtp, "ftplugin/tex_atp.vim"), "\n")[0]
	let stamp 	= get(getloclist(0),0, {'text' : '00-00-00_00-00'})['text']
	let stamp	= matchstr(stamp, '^"\s*Time\s\+Stamp:\s*\zs\%(\d\|_\|-\)*\ze')
    catch /E480:/
	let stamp	= "(no stamp)"
    endtry
    try
	exe 'lvimgrep /^\C\s*An\s\+Introduction\s\+to\s\+AUTOMATIC\s\+(La)TeX\s\+PLUGIN\s\+(ver\%(\.\|sion\)\=\s\+[0-9.]*)/gj '. split(globpath(&rtp, "doc/automatic-tex-plugin.txt"), "\n")[0]
	let l:version = get(getloclist(0),0, {'text' : 'unknown'})['text']
	let l:version = matchstr(l:version, '(ver\.\?\s\+\zs[0-9.]*\ze)')
    catch /E480:/
	let l:version = "(no version number)"
    endtry
    call setloclist(0, saved_loclist) 
    redraw
    let g:atp_version = l:version ." (".stamp.")" 
    return "ATP version: ".l:version.", time stamp: ".stamp."."
endfunction
"}}}
" atplib#various#Comment {{{
function! atplib#various#Comment(arg)

    " remember the column of the cursor
    let col=col('.')
     
    if a:arg==1
	call setline(line('.'),g:atp_CommentLeader . getline('.'))
	let l:scol=l:col+len(g:atp_CommentLeader)-4
	call cursor(line('.'),l:scol)
    elseif a:arg==0 && getline('.') =~ '^\s*' . g:atp_CommentLeader
	call setline(line('.'),substitute(getline('.'),g:atp_CommentLeader,'',''))
	call cursor(line('.'),l:col-len(g:atp_CommentLeader))
    endif

endfunction "}}}
" {{{ atplib#various#DebugPring
function! atplib#various#DebugPrint(file)
    if a:file == ""
	return
    endif
    let dir = getcwd()
    exe "lcd ".g:atp_TempDir
    if filereadable(a:file)
	echo join(readfile(a:file), "\n")
    else
	echomsg "No such file."
    endif
    exe "lcd ".escape(dir, ' ')
endfunction
function! atplib#various#DebugPrintComp(A,C,L)
    let list = split(globpath(g:atp_TempDir, "*"), "\n")
    let dir = getcwd()
    exe "lcd ".g:atp_TempDir
    call map(list, "fnamemodify(v:val, ':.')")
    exe "lcd ".escape(dir, ' ')
    return join(list, "\n")
endfunction
"}}}
" vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1
colors/coots-beauty-256.vim	[[[1
266
" Description: 	Vim color file
" Maintainer:	Marcin Szamotulski  <mszamot at gmail dot com>
" Note:		This file is a part of Automatic Tex Plugin for Vim.
" URL:		https://launchpad.net/automatictexplugin

" This color scheme was based on "Ocean237" theme by Chris Vertonghen.

set background=dark

highlight clear
if exists("syntax_on")
    syntax reset
endif

let g:colors_name="coots_beauty_256"

highlight Normal         cterm=none           ctermfg=252 ctermbg=233	guifg=white	guibg=#1c1c1c
highlight NonText        cterm=none           ctermfg=105 ctermbg=233	guifg=#1c1c1c	guibg=#1c1c1c 

highlight Visual         		      ctermbg=238				guibg=gray35
highlight VisualNOS      cterm=bold,underline ctermfg=57  ctermbg=233

highlight Cursor         cterm=none           ctermfg=15  ctermbg=93	guifg=#000000	guibg=#8A4C98
highlight CursorIM       cterm=bold           ctermfg=15  ctermbg=93	guifg=#000000	guibg=#8A4C98
"highlight CursorColumn
highlight CursorLine	cterm=none		ctermfg=none ctermbg=53           	guibg=#111111 gui=none

highlight Directory      			ctermfg=5   ctermbg=233	guifg=DarkViolet	guibg=#1c1c1c

highlight DiffAdd        cterm=none           	ctermfg=15  ctermbg=56  guifg=white	guibg=SlateBlue4 gui=bold
highlight DiffDelete     cterm=none           	ctermfg=19  ctermbg=125	guifg=VioletRed	guibg=DeepPink4
highlight DiffChange     cterm=none           	ctermfg=173 ctermbg=125	guifg=salmon	guibg=DeepPink4
highlight DiffText       cterm=bold           	ctermfg=white ctermbg=125  guifg=white	guibg=DeepPink4

highlight Question       cterm=bold           	ctermfg=33  ctermbg=233 guifg=#0087ff	guibg=#1c1c1c
highlight ErrorMsg       cterm=bold            	ctermfg=160 ctermbg=233 guifg=#d70000	guibg=#1c1c1c
highlight ModeMsg              			ctermfg=33  ctermbg=233 guifg=#0087ff	guibg=#1c1c1c
highlight MoreMsg        	           	ctermfg=39  ctermbg=233 guifg=#00afff	guibg=#1c1c1c
highlight WarningMsg    cterm=bold           	ctermfg=161 ctermbg=233 guifg=#d7005f	guibg=#1c1c1c

highlight LineNr                              	ctermfg=57 ctermbg=233	guifg=#837598	guibg=#1c1c1c
highlight Folded  				ctermfg=57 ctermbg=233	guifg=#837598	guibg=#1a1a1a
highlight FoldColumn     cterm=none           	ctermfg=green ctermbg=233 guifg=#5CB80C guibg=#1c1c1c
"highlight SignColumn

highlight Search         cterm=bold           	ctermfg=black  	ctermbg=226	guifg=black guibg=yellow
highlight IncSearch      cterm=bold        	ctermfg=black  	ctermbg=red	guifg=gold guibg=#1c1c1c
highlight MatchParen     			cterm=none    ctermfg=230        ctermbg=54	guifg=#1c1c1c guibg=gold

highlight PMenu          ctermbg=18 ctermfg=39  
highlight PMenuSel       ctermbg=39 ctermfg=18
highlight PMenuSBar      ctermbg=white ctermfg=33
highlight PMenuThumb     ctermbg=white ctermfg=33

highlight SpecialKey     ctermfg=129    ctermbg=233			 guifg=DarkViolet
highlight StatusLine     cterm=none     ctermfg=226 ctermbg=232		 guifg=#111111 guibg=wheat1
highlight StatusLineNC   cterm=none     ctermfg=245 ctermbg=232		 guifg=#111111 guibg=snow4	 
highlight default User1		 cterm=bold	ctermfg=226 ctermbg=232	gui=bold guifg=DeepPink4  	guibg=#111111	 
highlight default User2		 cterm=none	ctermfg=red ctermbg=232		 guifg=Khaki1  		guibg=#111111
highlight default User3		 cterm=none	ctermfg=226 ctermbg=232		 guifg=BlueViolet   	guibg=#111111

highlight VertSplit      cterm=none     ctermfg=green   ctermbg=233	 guifg=#1c1c1c	  guibg=DeepSkyBlue4
highlight WildMenu       cterm=bold     ctermfg=0   ctermbg=118

highlight Title          cterm=bold           	ctermfg=226 	ctermbg=232

"highlight Menu
"highlight Scrollbar
"highlight Tooltip

"          Syntax         Groups
highlight Comment        cterm=none           	ctermfg=90 ctermbg=233		guifg=Magenta4

highlight Constant       ctermfg=125          	ctermbg=233			guifg=DeepPink3
highlight String         cterm=none           	ctermfg=27   ctermbg=233	guifg=RoyalBlue1
"highlight Character
highlight Number         cterm=none           	ctermfg=161  ctermbg=233	guifg=DeepPink2
highlight Boolean        cterm=none           	ctermfg=161  ctermbg=233	guifg=DeepPink1
"highlight Float

highlight Identifier     		      	ctermfg=39			guifg=DodgerBlue
highlight Function       cterm=bold           	ctermfg=White   		guifg=White 		gui=bold

highlight Statement      cterm=none           	ctermfg=135			guifg=MediumOrchid
"248
highlight Conditional    cterm=none           	ctermfg=27   ctermbg=233	guifg=SlateBlue2
highlight Repeat         cterm=none           	ctermfg=82   ctermbg=233
"highlight Label
highlight Operator       cterm=none	      	ctermfg=40   ctermbg=233	guifg=Chartreuse1
highlight Keyword        cterm=none           	ctermfg=197  ctermbg=233	guifg=DeepPink1
highlight Exception      cterm=none           	ctermfg=82   ctermbg=233	guifg=Chartreuse1

highlight PreProc        ctermfg=82						guifg=DeepPink1
highlight Include        cterm=none           	ctermfg=130  ctermbg=233
highlight Define         cterm=none           	ctermfg=39   ctermbg=233
highlight Macro          cterm=none           	ctermfg=39   ctermbg=233
highlight PreCondit      cterm=bold           	ctermfg=125  ctermbg=233

highlight Type           cterm=none           	ctermfg=82               	guifg=LawnGreen
highlight StorageClass   cterm=none           	ctermfg=21   ctermbg=233
highlight Structure      cterm=none           	ctermfg=21   ctermbg=233
highlight Typedef        cterm=none           	ctermfg=21   ctermbg=233

" $, $$:
highlight Special        cterm=none	      	ctermfg=93			guifg=BlueViolet
"249
"tex math mode
"highlight SpecialChar
"highlight Tag:
"highlight Delimiter
"highlight SpecialComment
"highlight Debug

highlight Underlined     cterm=underline      	ctermfg=102 ctermbg=233		gui=underline
highlight Ignore         ctermfg=67

"highlight SpellBad       ctermfg=21           	ctermbg=233
"highlight SpellCap       ctermfg=19           	ctermbg=233
"highlight SpellRare      ctermfg=18           	ctermbg=233
"highlight SpellLocal     ctermfg=17           	ctermbg=233

highlight Todo           ctermfg=21           ctermbg=233	guifg=DeepPink guibg=#1c1c1c	gui=underline,bold

highlight helpNormal		ctermbg=235
highlight helpHyperTextJump 	ctermfg=57
highlight helpBar 		ctermfg=57
highlight helpStar		ctermfg=27	

highlight TabLine	cterm=none	ctermfg=white 	ctermbg=240
highlight TabLineFill 	cterm=none	ctermfg=white 	ctermbg=240
highlight TabLineSel	cterm=bold	ctermfg=white	ctermbg=57
"highlight TabLineSel	cterm=bold	ctermfg=white	ctermbg=197
" \command
highlight texDelimiter			ctermfg=161	ctermbg=233	guifg=MediumVioletRed
" \begin, \end:
highlight texSectionMarker		ctermfg=238	ctermbg=233	guifg=FireBrick		gui=bold
highlight texSection	cterm=bold	ctermfg=242	ctermbg=233	guifg=FireBrick2	gui=bold
" highlight texSectionName						guifg=FireBrick
highlight texDocType			ctermfg=90	ctermbg=233	guifg=DeepPink4
highlight texInputFile			ctermfg=90	ctermbg=233	guifg=DeepPink4
highlight texDocTypeArgs		ctermfg=161	ctermbg=233	guifg=DeepPink2
highlight texInputFileopt		ctermfg=161	ctermbg=233	guifg=DeepPink2
highlight texType			ctermfg=40	ctermbg=233	guifg=green3
highlight texTypeStyle			ctermfg=40	ctermbg=233	guifg=green3
highlight texMath			ctermfg=245	ctermbg=233	guifg=DarkKhaki
highlight texStatement 			ctermfg=54	ctermbg=233	guifg=DeepPink3
highlight Conceal 			ctermfg=54	ctermbg=233	guifg=DeepPink3		guibg=#1c1c1c
highlight texString			ctermfg=39	ctermbg=233	guifg=DodgerBlue
highlight texSpecialChar		ctermfg=39	ctermbg=233	guifg=DodgerBlue
highlight texRefZone							guifg=DeepPink2		gui=bold
highlight texCite							guifg=DeepPink4
highlight texRefOption							guifg=HotPink4
highlight texComment			ctermfg=125			guifg=#7963CA

" texlog /syntax file available in Automatic Tex Package/
hi texlogKeyword		ctermfg=90 cterm=bold		guifg=magenta4	gui=bold
hi texlogLatexKeyword		ctermfg=white cterm=bold 	guifg=white gui=bold
" hi texlogBrackets		Special
hi texlogOpenOut		guibg=magenta4	guifg=white
hi texlogWarningKeyword		guifg=DeepPink4 gui=bold
hi texlogPath			guifg=PaleVioletRed4
 
hi texlogLatexInfo 		ctermfg=90 cterm=bold	guifg=magenta4	gui=bold
 
hi texlogOutputWritten		ctermfg=90 cterm=bold	guifg=magenta4	gui=bold
hi texlogFileName		guifg=magenta4 gui=bold
hi texlogPages			guifg=magenta4 gui=bold
hi texlogChapter		ctermfg=90 cterm=bold	guifg=magenta4	gui=bold
" 
hi texlogLatexFontInfo 		ctermfg=90 cterm=bold	guifg=magenta4	gui=bold
hi texlogLatexWarning 		guifg=OrangeRed guibg=DeepPink4 gui=bold
hi texlogLatexFontWarning 			guifg=DeepPink4 gui=bold
hi texlogPackageWarning		                guifg=DeepPink4 gui=bold
hi texlogPdfTeXWarning		guifg=OrangeRed guibg=DeepPink4 gui=bold
hi texlogPackageInfo 		ctermfg=90 cterm=bold	guifg=magenta4	gui=bold
" hi texlogError 		Error
" 
hi texlogLineNr			guifg=OrangeRed3
hi texlogPageNr			guifg=OrangeRed3
" 
hi texlogDocumentClass		ctermfg=57 cterm=none guifg=BlueViolet gui=none
hi texlogPackage		ctermfg=90 cterm=bold	guifg=magenta4	gui=bold
hi texlogFile			ctermfg=90 cterm=bold	guifg=magenta4	gui=bold
hi texlogCitation		ctermfg=90 cterm=bold	guifg=magenta4	gui=bold
hi texlogReference		ctermfg=90 cterm=bold	guifg=magenta4	gui=bold
hi texlogOverfullBox		guifg=PaleGoldenRod
hi texlogUnderfullBox		guifg=PaleGoldenRod
hi texlogTooWide		guifg=PaleGoldenRod
hi texlogRedefining		guifg=PaleGoldenRod
hi texlogRedeclaring		guifg=PaleGoldenRod
hi link texlogSourceSpecials	texlogKeyword
hi link texlogEnabled		texlogKeyword
hi link texlogLineParsing	texlogKeyword
hi texlogMultiplyDefined	guifg=PaleGoldenRod
hi texlogScope			guifg=DarkOrange3 

hi texlogFont			guifg=DarkOrange4
hi texlogFontB			guifg=DarkOrange4
hi texlogFontSize		guifg=DarkOrange4
hi texlogFontShapes		ctermfg=90 cterm=bold	guifg=magenta4	gui=bold
" 
hi texlogDate			guifg=purple3
hi texlogVersion		guifg=purple3
" \chapter, \section, ... {theorem} {definition}

highlight Error          ctermfg=196         	ctermbg=233
highlight SpellErrors  	 cterm=underline      	ctermfg=darkred ctermbg=233
highlight SpellBad       ctermfg=196         	ctermbg=233
highlight SpellCap       ctermfg=202         	ctermbg=233
highlight SpellRare      ctermfg=203         	ctermbg=233
highlight SpellLocal     ctermfg=202         	ctermbg=233

hi bibsearchInfo 	ctermfg=33			guibg=DeepPink
hi bibsearchComment	cterm=bold 	ctermfg=27	guifg=blue		gui=bold 
hi bibComment2		cterm=bold 	ctermfg=30	guifg=SeaGreen4		gui=bold
hi bibsearchCommentContents cterm=none	ctermfg=30	guifg=SeaGreen4		gui=none
hi bibsearchType			ctermfg=24	guifg=MediumVioletRed
" hi bibsearchEntryData						ctermfg=magenta
hi bibsearchKey		cterm=bold 		ctermfg=white	guifg=white	gui=bold
hi bibsearchEntry 				ctermfg=33	guifg=DeepSkyBlue
    hi bibsearchField 				ctermfg=green	guifg=SlateBlue4
	hi bibsearchEntryKw			ctermfg=white	guifg=SlateBlue3
	hi bibsearchBrace			cterm=bold	guifg=white gui=bold
	hi bibsearchVariable 			ctermfg=white	guifg=white

" ATP toc file
highlight atp_filename						guifg=FireBrick
highlight atp_linenumber	cterm=bold	ctermfg=27	guifg=PeachPuff4
highlight atp_number 				ctermfg=33	guifg=sienna
highlight atp_chapter 		cterm=bold 	ctermfg=white	guifg=seashell2		gui=bold
highlight atp_section				ctermfg=30	guifg=seashell4
highlight atp_subsection			ctermfg=24	guifg=seashell4
highlight atp_abstract	cterm=bold	ctermfg=gray		guifg=seashell2		gui=bold

" ATP label file
highlight atp_label_filename					guifg=DeepPink4		gui=bold
highlight atp_label_linenr cterm=bold	ctermfg=white		guifg=maroon
" highlight atp_label_name 		ctermfg=green		guifg=chartreuse
highlight atp_label_name 					guifg=DeepPink2		gui=bold

highlight atp_statusline 	cterm=bold	ctermfg=green 	ctermbg=233

highlight atp_statustitle 	cterm=bold	ctermfg=grey 	ctermbg=233  
highlight atp_statussection 	cterm=bold	ctermfg=yellow 	ctermbg=233  
highlight atp_statusoutdir 			ctermfg=grey 	ctermbg=233 

highlight link atp_Todo Normal

highlight ywtxt_todo	guifg=yellow gui=bold
highlight ywtxt_note	guifg=yellow gui=bold

highlight ywtxt_heading1 guifg=slateblue1 gui=bold 
highlight ywtxt_heading2 guifg=slateblue gui=bold 
highlight ywtxt_heading3 guifg=slateblue4 gui=bold 
highlight ywtxt_heading4 guifg=darkslateblue gui=bold 
highlight ywtxt_bold 		cterm=bold 	gui=bold
highlight ywtxt_italic 		cterm=italic  	gui=italic
highlight ywtxt_underline 	cterm=underline gui=underline
highlight ywtxt_comment guifg=honeydew4

" vim
highlight vimCommentTitle	cterm=bold	ctermfg=white

" Easy Motion
highlight EasyMotionTarge	cterm=bold ctermfg=red guifg=red 
highlight EasyMotionShade	ctermbg=232 guibg=gray17
doc/automatic-tex-plugin.txt	[[[1
5606
*automatic-tex-plugin.txt* LaTeX filetype plugin	Last change: 15 May 2012

	    An Introduction to AUTOMATIC (La)TeX PLUGIN (ver. 11)
			by Marcin Szamotulski
		    mszamot [AT] gmail [DOT] com
-----------------------------------------------------------------------------

If you found this plugin useful or you have any kind of problems with running
it or some ideas to share, you are cordially invited to write to me:
mszamot@gmail.com. Voting at Vim site is also welcome ;) .

-----------------------------------------------------------------------------
			    ABSTRACT ~

This is a filetype plugin for Vim to comfortably write [TeX], [LaTeX],
 [PdfLaTeX],...  documents, which provides functionality not met in other
plugins. It makes you [FREE] from compiling procedure, making this process
automatic using autocommands. It also provides useful mappings and other
many other commands: to analyse your .log file, to see the table contents, to
search for a label, to search in bib files or to find a macro definition
matching a pattern, or even to find and preview fonts in your tex
distribution. The features include a multi-functional tab completion for:
commands, environment names, packages, input files, bib files, bst files,
colours, closing brackets and environments (preserves nesting),... etc. To
have full functionality you need: python (with nonstandard psutil library, see
|atp-requirements-python| how to get it), pdffonts available in the package
'app-text/poppler' (at least in Gentoo).  Another good tool is texdoc, which
is a part of TexLive - these days standard TeX distribution for Linux, and
MikTeX on Windows.
------------------------------------------------------------------------------

			FEATURES INCLUDE: ~
------------------------------------------------------------------------------
* background compilation, debugging modes, progress bar
* command to make the document (cross references, references, index, tables
  of contents) |atp-:MakeLatex|,
* completion for commands, closing environments (even nested), package names,
  citations and labels. Support for some latex packages,
	see |atp-completion|, 
* forward/inverse searching:
  	see |atp-:SyncTex|, |atp_inverse_search|,
* table of contents which allows to switch between different sections, files, 
  but also to delete and paste sections:
	see |atp-:TOC|, |atp-toc-window|,
* list of labels which allows to see the context of a label:
	see |atp-:Labels|,
* a command to get bib data from the AMSRef web page http://www.ams.org/mathscinet-mref:
	see |atp-:AMSRef|,
* a powerful function to search in bibliographic files (bib files):
	see |atp-bibsearch|,
* a command to list ToDo lines:
	see |atp-:ToDo|,
* a command to search for a macro definition (multi-line support):
 	see |atp-:Dsearch|,
* a command to search and PREVIEW fonts in your latex distribution:
 	see |atp-:FontSearch|, and |atp-:FontPreview|,
* indentation.

==============================================================================
SOURCEFORGE						*atp-sourceforge*

  - The project is hosted on SourceForge:
    http://sourceforge.net/projects/atp-vim/

DONATE     						*atp-donate*
    You can [DONATE] for this project through your [PayPal] account (my email
    is <mszamot [AT] gmail [dot] com>). This will be highly appreciated. You
    can also feel like you are supporting my [PhD] in Mathematics :). Whether
    you donate or not you are always cordially invited to give suggestions,
    feature requests, bug reports or just to write that you like it or not :).
							Thank You. ~
    You can use this link:							
    https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=3NMU7FEEPVG7Q

    Note: The donations are accepted through PayPal, if you are from Europe
    and you want to donate Euro, use your PayPal account rather than
    SourceForge link where you cannot donate Euro (avoiding twice money
    exchange).

  							*atp-mailing-list*
  - There is a mailing list which will serve for: feature requests, bug
    reports, suggestions. You can subscribe at:
    https://lists.sourceforge.net/lists/listinfo/atp-vim-list

  - There is also a new wiki page: (as for now it only includes features of
    ATP - it looks nice :)
    http://sourceforge.net/apps/mediawiki/atp-vim/index.php?title=Main_Page

  - For detailed list of changes you can look at:
    http://atp-vim.svn.sourceforge.net/viewvc/atp-vim/trunk/?sortby=rev&view=log

  - Project news can be tracked through sourceforge watch feature (you need
    sourecforge account)

  - SourceForge hosts stable releases (also available on Vim web page) but
    also snapshots of unstable developed new version. The snapshots might
    contains fixes and new features which might not yet work well, or might
    change (commands, maps, etc ...).
    

==============================================================================
TABLE OF CONTENTS 					*atp*
                                                	*atp-help-toc*
	|atp-news|			News.
	|atp-installation| 		Installation.								
	    |atp-and-other-plugins|
	|atp-commands| 			Functions and commands:
	some most important commands: ~
	    compile ~
		|atp-:TEX|
		|atp-:MakeLatex|
		|atp-:Bibtex|
		|atp-:DebugMode|
		|atp-:ShowErrors|
		|atp-:ErrorFormat|
		|atp-:Kill|
	    viewer ~
		|atp-:View|
		|atp-:SyncTex|		forward searching,
	    diff ~
		|atp-:Wdiff|
	    motion ~
		|atp-:TOC|
		|atp-:F|
		|atp-:B|
		|atp-:Tags|		make tags file,
	    search ~
		|atp-:Dsearch|		definition search,
		|atp-:S|		search in projects.

	|atp-toc-window|		Commands/maps defined in Table of Contents window 
				      and Labels window. Includes folding from toc.
	|atp-folding|			Folding.
	|atp-bibtex|			File type plugin for bibtex.
	|atp-bibsearch|			Searching in bib files.
	|atp-completion|       		How to use and configure completion
	|atp-configure| 		How to configure to your needs.
	|atp-ProjectFiles|		A note how to write project files within ATP.
	|atp-ProjectScript|		A script executing project specific settings.
	|atp-mappings|  		Mappings.
	    |atp-imaps|
		|atp-imaps-fonts|
		|atp-imaps-greek-letters|
		|atp-imaps-environments|
		|atp-imaps-math-misc|
		|atp-imaps-math|
		|atp-imaps-diacritics|
	|atp-abbreviations|		Abbreviations.
	|atp-errors|  			Debugging ATP.
	|atp-editing|			Editing tools.
	|atp-requirements|  		Requirements.
	|atp-viewers| 			Note about viewers,
					with [reverse_searching] for Okular, Xpdf and Skim
	|atp-tips|			Some tex oriented tips.
	|atp-highlight|			Colours and syntax files.
	|atp-remarks|  			Final remarks.
	|atp-development|
	|atp-copy-rights|		Copy Rights.

	
Note on usage: type :help atpCTRL-d to see all the helptags. To see help tags
for all the defined functions :help atp*()CTRL-d, mappings: :help atp-mapCTRL-d

================================================================================
NEWS							*atp-news*
>
 ======================
 Changes in version 10.6.5
<
 NOTE: You should remove the file:
     ~/.vim/ftplugin/ATP_files/packages/amsmath.vim
 Then ATP completion will work better, since ATP can now scan package and
 documentclass files (.sty, .cls) for commands and options.

 NOTE: I change the name of the script at vim.org to AutomaticLaTeXPlugin
 (with capital X), if you install ATP via Vim-Addon-Manager (or other vim
 plugin manager) this might affect path were the atp_RevSearch.py script is
 located. In this case you might need to adjust the setting of reverse search
 in your viewer (Okular, Xpdf, ...).

 NOTE: It was found that 'relativenumber' option slows down vim when edditing
 tex files (at least for some users).

 QUICK REFERENCE GUIDE:~
 You can download a quick reference guide for ATP from:
     http://atp-vim.sourceforge.net/atp_quickref.pdf
 It should be easier now to go through ATP features.

 If you set |g:atp_ParseLog| and |g:atp_Compiler|="python", then ATP will
 rewrite the log file so that the output is readable for vim |quickfix| using
 |errorformat|. The advantage is for project files, where it is important to
 correctly read the file position of the error. In addition there is one more
 |atp-:ShowErrors| flag 'O' which shows 'overfull \hbox' messages. Also note
 that the flag 'w' (for warnings) excludes font warning messages.  
 NOTE: See also |atp-:Cgetfile| (!!! This command is only defined for vim version
 < 7.3.468, my patch 468 introduces a new autocommand which is used to rewrite
 the log file, so check out the latest vim version !!!).

 |atp-:ErrorFormat| accepts "+{+flag}-{-flag}" as an argument.

 |g:atp_Signs|=0 by default.

 |g:atp_indent|=1 by default, then LatexBox indentation file is used.   

 |atp-gf| works well with \bibliography{} command.

 See ':help atp-omap-<C-d>' for the defined operator maps. 
 |atp-vi(|, ... , |atp-va}| maps.

 Support for subfiles.sty package:~
 Compilation of parts of a project (using subfiles package).
 |atp-:TEXL|, |atp-:ViewL|, |atp-:SyncTexL|, see also |b:atp_autex| (when set
 to 2 automatic compilations of subfiles is turned on).

 |atp-:S| command has additional flag 'x', when used the
 |v:searchforward| value will not be changed.

 TABLE OF CONTENTS:~
 |atp-:TOC| was rewritten in python so that it works well with project files.
 If your vim is compiled without python the old ToC will be used. 

 TOC and Labels windows are clicable: acts like <space> = go to section and
 leave TOC/Labels window open. 
 See also |atp-:RemoveFromToC| command.

 NEW DEBUG MODES:~
 See |atp-autosilent|, |atp-autodebug| and |atp-autoDebug| debug modes.
 Previously, by default QuickFix window was closed when there was no error.
 Now this behaviour is reserved only for |atp-autosilent|, |atp-autodebug|,
 and |atp-autoDebug| modes.

 omap \w and vmap \w to repeat last wrapping command (like \it, \sf, \em, ...)
 (see |atp-omap-\w| and |atp-omap-WrapSelection|)

 See |g:atp_diacritics| (used instead of g:atp_imap_diacritics_inteligent).

 |atp-:ErrorFormat| and |atp-:ShowErrors| have a flag 'h' instead of 'O' which
 shows both 'Underfull \hbox' and 'Overfull \hbox' messages'.

 Local project script (.project.vim file) may contain |:set|/|:setl|
 statements which will be executed after |vimrc| and |atprc| files.
 These statements are executed only once (per project file).

 CHANGE IN MAPS: ~
 As suggested by F.Heiderich: #< and #> are now maps for \langle and \rangle.

 New commands: |atp-:TexDef|, |atp-:KpsewhichEdit|. They are defined in
 plugin/tex_atp.vim script, so you can use them not only inside tex files.
>
 ======================
 Changes in version 10.6.4
<
 ATP normal r map is working better, that is |.| works well with |atp-r| map.

 |g:atp_OpenAndSyncSleepTime| = "500m"	-- sleep time between the time when
 ATP finds the viewer working and syncing (forward searching) for the command
 |atp-:View|! (with bang) (this is time left for the viewer to open the file).

 Plus some new package files for completion: showidx, makeidx, syntonly and
 a better completion for the \includeonly{} command (which removes items from
 completion menu which are already included).

 Count added to |atp-]%| and |atp-[%|.

 |atp-:TexAlign| works with smallmatrix environment.

 Completion scans package and documentclass files for options (if vim is
 compiled with |+python|).
>
 ======================
 Changes in version 10.6.3
<
 A small bug fixed when opening a new tex buffer.

 Omni completion changed:
	 (Expert Mode) Tab Completion is mapped to <C-X><C-O>
     (Non Expert Mode) Tab Completion is mapped to <C-X>o
 This is the default, if you want to use <Tab> and <S-Tab> keys set
 |g:atp_tab_map| to 1 in your |vimrc| or |atprc| file.

 For some reasons it is better to map completion to <C-X><C-O> than to use
 'omnicomplete' option (as it was done in 10.6.2). Using the option sometimes
 issues errors (when modifying text) also setting cursor position to the right
 place is impossible (in more advanced completions, like closing
 environments).

 Note also that g:atp_no_tab_map has changed to |g:atp_tab_map|.
>
 ======================
 Changes in version 10.6.2
<
 Omni completion	-- ATP Tab completion now works as Omni Completion, see
			   |compl-omni|, the non expert mode completion is
			   mapped to <F7> key. The <Tab> key is not mapped. If
			   you want to use <Tab> and <S-Tab> for completion,
			   as it was done before, just put 'let
			   |g:atp_tab_map|=0' in your |vimrc| or |atprc|
			   files.

			   Note that omni completion might give the 'Pattern
			   not found' error, when closing environments or
			   brackets - you can ignore this message (it is not
			   possible to turn it off, and working it around will
			   take to much time).
	
 	completion	-- memoir document class completion: document class options,
			   and some commands,
			-- bibref package added.

 % motion		-- changes the jump list (this is vim compatible
			   behaviour (see |jump-motions|)
			-- omap % added. Now to delete an environment just put
			   the cursor over \begin or \end command and use 'd%'.
			   The same will work if you want to delete (:), [:],
			   {:} or $:$ pairs.

 { and } normal motions	-- also work in visual mode (see |}| and |{|).

 |atp-:Yank| and |atp-:Paste| (inside bib search) changed.  Also yanking in
 toc (the section key) is in more vim style.

 |atp-:PasteSection| with bang "!" puts section before rather than after.

 At the end of |atp-tips| I show how to make w b and aw work slightly better
 (this is experimental code). 

 |atp-:ChangeLabel|       -- a new command for changing labels across the
			   project.

 |atp-:WordCount|         -- range added, if the file type is 'tex' also
			   doesn't count the preambule.

 |atp-:View| 		-- instead of :ViewOutput command.
>
 ======================
 Changes in version 10.6.1
<
 In the |atp-:BibSearch| window:
 :BibChoose is now split into two commands: 
 |atp-:Yank| and |atp-:Paste|, the maps 'y', 'c' and 'p', 'P' can be invoked
 with a count. |atp-:Yank| by default uses the " register.

 |atp-:SyncTex| is now mapped to |atp-\f|, instead of t, which was not
 compatible with |t| vim command. It is easy to remember |atp-\f| = like forward
 search ;)

 New normal mode wrapping operator maps: see |atp-nmap-fonts| and
 |atp-nmap-bracket-wrappers|.

 Commands to find maps:
    :Map[!]  {pattern}			|atp-:Map|
    :Nmap[!] {pattern}			|atp-:Nmap|
    :Imap[!] {pattern}			|atp-:Imap|
    :Smap[!] {pattern} 			|atp-:Smap|
    :Vmap[!] {pattern}			|atp-:Vmap|
    :Omap[!] {pattern}			|atp-:Omap|
    :Lmap[!] {pattern}			|atp-:Lmap|
There is another plugin: MapFinder 
    http://www.vim.org/scripts/script.php?script_id=3767
which defines them. The only Imap differs, here it is more specific to ATP,
since ATP defines and deletes some imaps on the fly not all of them are
visible with :imap command.

>
 ======================
 Changes in version 10.6
<
 The command |atp-:View| with bang (also <F3> map) opens and makes forward search.
 Reverse search (atplib#FindAndOpen() function) sets the "'" mark before
 changing text position.

 Folding: ~
 See |atp-folding| - thanks to Johannes Zellner for the simple (and fast)
 folding script.

 Imaps: ~
 ->, <- in tikz picture environment (but not in math) puts \draw[->] or \draw[<-].
 They are also disabled inside [:].

 Vmaps: ~
 'o, 'u	instead of 'ov and 'uv (\overline, \underline). This is compatible
 with imaps 'o and 'u.

 Some bug fixes. For example the algorithm for closing brackets is more
 reliable (should work in 100% cases ;).

 Cmap: ~
 <space> cmap for \_s\+, if |\v| is included (very magic) in the pattern (any where) then
 \_s+ is used as rhs.

>
 ======================
 Changes in version 10.5
<
 Thanks for all the vim karma points: if you look at all ftplugin scripts ATP has 8th
 rate and among ten most rated plugins it has 2nd best average rate: 3.71, while the
 first one has 3.73. If you find something in ATP which is not convenient, or
 you think it might be done in a more friendly way, let me know, I'm open for
 discussions :) 

 Here are the recent changes (excluding bug fixes):

 Signs			-- see |atp-signs| (and |signs|).
 :Unwrap		-- see |atp-:Unwrap| command (nmap <LocalLeader>u).

 See added note below |g:atp_texinputs|.
 The package variable names are changed, see |atp-completion-packages|.
>
 ======================
 Changes in version 10.2
<
  Skim (MacOS)                  -- support for "Skim" added (forward search)
                                   [thanks to Florian Heiderich].
                                   Read the necessary steps in |atp-Viewers-Skim|.

  Xpdf				-- support for inverse searching added (Xpdf -> vim)
				   thus both inverse and forward searching
				   works for Xpdf (and Okular). See
				   |atp-Viewers-Xpdf| how to set it.

  :MakeLatex [mode]		-- mode is one of silent/debug/Debug. Will
				   also show bibtex/biber/makeidx error
				   code/debug info.

  :Dictionary {word}		-- an interface to http://www.impan.pl/Dictionary/.
  					see |atp-:Dictionary| (with map =d
					using |<cword>| under the cursor).

  |atp-:Edit|			-- instead of :EditInputFile

  :ShowErrors e			-- fixed (finally!)
  :TexAlign			-- can manage table environments and also
				   join lines which do not end with \\, see
				   |g:atp_TexAlign_join_lines| how to set this.

  'iskeyword'			-- is set using g:tex_isk variable. This is
				   compatible with the standard tex syntax
				   file.
  :TexAlign!			-- bang added+some fixes, see |atp-:TexAlign|.

								|atp-r|
  Replace()			-- if |g:atp_VimCompatible| is 0 then the
				   normal |r| will be overwritten with another
				   function with the following feature:
				   if you do |atp-r| over one of the brackets:
				   (:), {:}, [:] then r(, r{, r[ (and r), r},
				   r]) will change both: the opening and the
				   closing bracket. Otherwise, i.e. over any
				   other character, or rc where c is other
				   than opening bracket at opening position or
				   closing bracket at closing position,
				   |atp-r| will work the same as |r|.

  New imaps:
  l*, L*	\wedge, \bigwedge (l = lattice theoretic, meet)
  l+, L+	\vee,	\bigvee   (join)
  wedge is also under #& but #ve (for \vee) and #V (for \bigvee) are removed,
  since they were interfering with #ve for \varepsilon.

  Greek Letter Maps: are disabled when the previous character is '\'. So you
  can type '\#a' with the default value of |g:atp_imap_leader_1| and it will
  not transform into '\\alpha'.

  TOC:
  map _				-- set section: focus main window on the
				   section under cursor and jump back to TOC.
  map & vmap zc			-- fold sections/chapters/... . Has one
				   limitation: cannot fold subsection if
				   section in which it sits is folded.
				   You can fold several sections at once using
				   visual mode (subsections will not be
				   folded in right way though).

>
 ======================
 Changes in version 10
<
  If you use <Shift-Tab> (i.e. non-expert mode for completion) to close
  a bracket, it will be put after the cursor, allowing you to write inside
  brackets. This doesn't work with \(:\) and other math pairs and closing
  environments.

  Closing brackets with <Tab> is much faster now.

  cmap <M-c> ^\%([^%]\|\\%\)*	- useful when searching for sth which
				  is not in a commented out.

  Both vmap and imap for \overline and \underline are using
  |g:atp_imap_over_leader|.

  The value of |g:atp_MapSelectComment| is now |=c| (it used to be _c)
  You can also use v|ip| over commented lines to select them.

  New math imaps: (|atp-imaps-math|)
  |-	\vdash
  -|	\dashv
  ++ 	\sum	(it is disabled now when typing X_++ or X^++)

  The command :Align (and thus also :TexAlign) are using ATP_strlen function to
  measure the string length. ATP sets g:Align_xstrlen="ATP_strlen" if
  'conceallevel' option is >0. If 'conceallevel' is reset to 0 ATP_strlen
  behaves like g:Align_xstrlen=2. (This needs Align plugin version higher than
  36, available at: http://drchip.0sites.net/astronaut/vim/#ALIGN .

  |atp-:TOC| and |atp-:Labels| commands when open together will be in one
  column with table of contents at the top.

  ]*, ]%, [*, [%  - skip comment maps, all works now in the same way. If 
  |g:atp_VimCompatible| is 1 they go to where comment starts/ends, if it is
  0 they go one line above/below. 

  cmap <M-c> will insert a pattern which match lines which are not a comment.


================================================================================
INSTALLATION                               		*atp-installation*

If you have .vmb (or .vba) file just open it in vim and source it (:so %<CR>).
You can also install ATP using Vim Addon Manager (VAM):
http://www.vim.org/scripts/script.php?script_id=2905
or GetLatestVimScipt plugin:
http://www.vim.org/scripts/script.php?script_id=642
Third option is to checkout svn repository with the command:
svn co https://atp-vim.svn.sourceforge.net/svnroot/atp-vim/trunk ~/.vim
If you use VAM you can checkout into your vim-addon directory
(~/.vim/vim-addons/AutomaticLaTexPlugin) and VAM will update it using svn
pull. In this way you will have always the most recent version of ATP.

Note: If you use Pathogen or VAM you need to restart all your vim servers if
you want revesre search to work, or at least use in each running server
pathogen#infect('addons'), or similar command with VAM (:ActivateAddons
AutomaticLatexPlugin).

     Necessary vim settings:
     |:filetype-plugin-on|
     |:filetype-indent-on|	(if you want to have automatic indentation for TeX files)
     |:syntax-enable|		(several features will not work properly without this option)

If you do not like colours you can still set syntax on but clear the highlight
colours (you should make a simple function which clears all the highlight
groups, because ':hi clear' will not give you what you want).

See |atp-requirements| for other ATP requirements or better go to:
http://atp-vim.sf.net/requirements.shtml web page.


GET ATP UPDATES ~
To get updates it is enough to use this command:
							*atp-:UpdateATP*
:UpdateATP[!]
	With bang update ATP to latest {UNSTABLE} snapshot, without to latest
	stable release. It makes a check if your version is the latest one. 
	If you have installed {UNSTABLE} snapshot and then you run :UpdateATP
	without a bang "!", then ATP will ask you if you want to DOWNGRADE to
	the last stable release.

	{UNSTABLE} snapshots contain small fixes, and rarely, major changes
	of important parts of ATP (what can produce new bugs).  

	|atp-:UpdateATP| works well with pathogen vim plugin.

	Requires python (consult the |feature-list|).

							*atp-:ATPversion*
:ATPversion	
	This command prints version information of ATP and the time stamp when
	this version was build. The time stamp is in format 'dd-mm-yy_HH-MM'.

--------------------------------------------------------------------------------
ATP AND OTHER PLUGINS					*atp-and-other-plugins*
							*atp-EasyMotion*
EasyMotion and ATP ~
    If you want to use EasyMotion vim plugin (which is quite handy):
	http://www.vim.org/scripts/script.php?script_id=3526
    You can set |g:atp_Compare|="". Alternatively, if you want to use the
    fastest comparing method of ATP, you can add to last line of
    s:EasyMotion() function (i.e. just above the |:endfunction| vimL keyword) in
    autoload/EasyMotion.vim: 
>
	    let b:atp_changedtick = b:changedtick
<   In older version of EasyMotion this function used to be inside
    plugin/EasyMotion.vim file.

    You might want to change g:EasyMotion_leader_key (see |easymotion-leader-key|), 
    because some maps of ATP are interfering with EasyMotion. For example "-"
    might be a good choice.  You can also try to change |maplocalleader| which
    is heavily used by ATP.

================================================================================
COMMANDS	                               		*atp-commands* *atp-:*
							
							*atp-compilation*
The main function is not seen by the user (it is called s:compiler, for those
who want to read the plugin). It executes tex compiler specified by the
variable |b:atp_TexCompiler|. It is executed as an autocommand by the line: >
	au! CursorHold $HOME*.tex silent call 's:auTeX()'
< where s:auTeX() is a simple function which calls s:compiler if the file
written on the disk and the buffer differ. There are two comparing mechanism,
the default one is using |b:changedtick-variable| , the seconds compares the
buffer with the on-disk version:
							*g:atp_Compare*
							*g:atp_compare_double_empty_lines*
							*g:atp_compare_embedded_comments*
	The default value is "changedtick". Then the |b:changedtick-variable|
	is used to find if there buffer differs and to run latex. With any other
	value a compare function will be used (which compares the buffer and
	the written file on the disk) - this method is much slower but has
	additional features: by default differences in comments are skipped
	(if you set |g:atp_compare_embedded_comments|=0 (the default is 1)
	then also the comments which do not start right at the beginning of
	line will be skipped). The second feature is to not see differences in
	amount of blank lines: two or more blank lines is the same as one
	blank line, for this set |g:atp_compare_double_empty_lines|=0, which
	is the default.

As you can see it will run if a key is not pressed during time defined by
option |'updatetime'| (see |CursorHold|) in the normal mode. If you type in
insert mode the file won't be compiled (and that's all right as you can be in the
middle of your very long formula). The value of |'updatetime'| which works
fine is around 1000ms (|'updatetime'| is set in milliseconds). Instead of
setting |'updatetime'| options directly you should set the variables
|b:atp_updatetime_insert| and |b:atp_updatetime_normal|. Here's an important
note on using CTRL-C (|i_CTRL-C|) in Vim:

							*g:atp_IMapCC*
    In vim the key combination CTRL-C (|i_CTRL-C|) in insert mode exists to
    normal without triggering the InsertLeave autocommands. In this way it
    doesn't changes the |'updatetime'| from |b:atp_updatetime_insert| to
    |b:atp_updatetime_normal|. If |g:atp_IMapCC|=1 then |_CTRL-C| is mapped to
    |i_CTRL-[| so the InsertLeave autocommands are parsed. However, it is
    a good habit to use |i_CTRL-C| while you are writing/editing and |i_CTRL-[| or
    |i_ESC| when you wish to see what you wrote (then TeX will be run
    quicker). If you follow this you can even set
    |b:atp_updatetime_normal|=1 (if you set it to 0 then the file will not
    be processed while Vim is in normal mode).

							*b:atp_updatetime_insert*
							*b:atp_updatetime_normal*
>
 b:atp_updatetime_insert = 4000	
 b:atp_updatetime_normal = 2000
< - These variables sets the value of |'updatetime'| vim option.
    Separate settings are for normal and insert mode. You can make
    |b:atp_updatetime_normal| even smaller so that the file is processed
    whenever you go out from insert mode to normal mode. These values will
    overwrite the original value of |'updatetime'| (unless you set both
    variables to 0)  so you should adjust them in order for the change to have
    an effect.

    If you set |b:atp_updatetime_insert|=0 the TeX compiler will not be called
    while Vim is in the insert mode. 

    If you set |b:atp_updatetime_normal|=0 the TeX compiler will not be called
    while Vim is in the normal mode.

							*b:atp_MaxProcesses*
>
 b:atp_MaxProcesses = 3
<
    When |g:atp_Compiler|="python" this variable will control the maximal
    number of simultaneous LaTeX processes in the background. If new process
    comes old and the number of processes is |b:atp_MaxProcesses| or bigger
    one appropriate number of processes is killed to have not more than
    |b:atp_MaxProcesses|. If you set it to 0 ATP will not control the number
    of running instances of LaTeX compiler. There is one more variable:

    							*b:atp_KillYoungest*
>
 b:atp_KillYoungest = 0
<
    When set to 0 (the default) oldest processes are killed, when set to
    1 youngest ones. If your file is big it might be better to kill youngest
    processes.

Coming back to compilation ... ~

Tex compiler is run with one options:
	-output-directory 
which points to a unique temporary file in a temporary directory |b:atp_TempDir| 

							*b:atp_autex*
You can switch off/on the function s:auTeX by pressing <S-F5> or by letting
the local to buffer variable |b:atp_autex|=1 (on) |b:atp_autex|=0 (off). It is
useful in some situations turn automatic compiling off. 
    Note: if you set |b:atp_autex|=2 the the automatic compilation will
    compile the currently edited subfile of your project (for this you need to
    use the subfiles package).
The key <S-F5> calls the command |atp-:ToggleAuTeX| which sets the variable
|b:atp_autex| and issue a message. You can also set this variable to 0 for
some files that are not supposed to be processed, for example:
>
	au BufRead texmf/*.tex let b:atp_autex=0
<
On start up |b:atp_autex| is set to 1 if the path of opened file is not under any
tex directory ('kpsewhich -show-path tex', except the current dir). For example,
files located under your local texmf tree will have b:atp_autex=0. Also for
files with other extension than the standard "tex" it will be set to 0.

							*atp-:ToggleAuTeX*
:ToggleAuTeX {arg}
	The {arg} is one of off/on/local. It sets b:atp_autex to 0/1/2
	respecively. If {arg} is omitted it changes: local->off (2->0),
	on->off (1->0) and off->on (0->1).

The second important variable |b:atp_TexCompiler| configures if you use TeX,
PdfTeX, LaTeX, PdfLaTeX and it should point to the program name so please do
not use capital letters.

Next variable to set is |b:atp_OutDir|. It configures where TeX
will put the output and where viewer and log analysing tools can find
appropriate files. 

The last top most important variable is |g:atp_keep| which is a list of extensions,
by default it is
    let g:atp_keep = [ "log", "aux", "toc", "bbl", "ind", "idx", "synctex.gz", 
		\ "blg", "loa", "toc", "lot", "lof", "thm", "out" ]
Files with this extension will be copied from |b:atp_OutDir| to the temporary
directory with appropriate name to be used when (La)TeX is compiling. (log file
will be only copied after it is created, other files will be copied back and
forth between you |b:atp_OutDir| and the temporary directory)

							*atp-compile.py*
There are two function compile which can compile your tex file: one written in
python (for portability reasons) and old one in bash. They work almost the
same with one small difference. The python code has some vim enhancements (for
example the progres bar).

The python code has a debug file compile.log under |g:atp_TempDir| will
contain all the errors issued by python, and 'compile.py.debug'
- debugging info printed by the |compile.py| script.

    							*g:atp_Compiler*
If for some reason you'd like to use the old 'bash' style script there is
a variable: >
	g:atp_Compiler = "python"
< just switch its value to "bash" (you don't need to restart vim).  OK, so
what is the difference: the python script uses psutil python library (probably
you need to install it, at least I had to.) It is for two purposes: to
determine if xpdf is running and secondly, more importantly to check if latex
is running. 
    							*b:atp_LatexPIDs*
The python script |compile.py| sends PID numbers of latex processes to vim
variable |b:atp_LatexPIDs|. Then the function which makes the status line for
ATP has a python code to check if the latex PIDs are still valid processes.
This is more accurate than the method used with bash compiler (before running
latex increase variable |b:atp_running| and decrease after getting signal that
latex has ended). In many situations this was failing.  The new method works
better, however it shows that latex is running after slightly longer period of
time (not that first python must run the script and then run latex). 

							*b:atp_TexReturnCode*	
The variable |b:atp_TexReturnCode| stores the return code of compilation.

See |atp-requirements-python| for python libraries that are used by ATP.

-------------------------------------------------------------------------------
CALL BACK AND DEBUG MODE				*atp-callback*
							*atp-debug-mode*
	By default the call back mechanism is turned on (g:atp_callback=1)

	When call back mechanism is set, which is by default if you run gui
	version, if you invoke 'vim' from command line you need to add
	'servername' variable, it might be desirable to alias Vim to to >
			vim --servername VIM 
< 	you have additional functionalities:
							*atp-signs*
							*g:atp-Signs*
        * if you set |g:atp_Signs| to 1 (the default is 0) call back and
	  |atp-:ShowErrors| will use |signs| to mark errors and warnings.

							*atp-status-line-notification*
							*g:atp_statusNotif*
	* Status Line Notification: status line can show if tex is running >
		let g:atp_statusNotif = 1
<	  If unset you will get a message when compiler ends. If set the
	  number next to the name of your compiler indicates how many
	  instances are currently running. If |g:atp_ProgressBar|=1 then also
	  progress information of TeX compiler will be shown.

	  It can also show if other programs such as bibtex, biber or makeidx
	  are curently running.
	
	* The log file will be automatically read after compilation (|:cgetfile|).
	  						*g:atp_cgetfile*
	  The command |:cgetfile| will be run when you open new files, this
	  nicely works with |:edit| command but not |:split| if you want to keep
	  the old log file in QuickFix window. If this is the case set >
	     let g:atp_cgetfile = 0 
<   	  The default value is 1.	

	* Debug mode is set by the value of |t:atp_DebugMode|, you can set or
	  see its value using |atp-:DebugMode| command (with completion for
	  debug modes).
							*t:atp_DebugMode*	
							*atp-debug-mode-silent* *atp-debug-mode-autosilent*
							*atp-silent* *atp-autosilent*
	* if |t:atp_DebugMode| 	= 'silent' or 'autosilent'
	  :DebugMode silent
	  nmap <LocalLeader><LocalLeader>s
	       You will not get any message from compilation. 

	       In 'autosilent' mode the quick fix window will be automatically
	       closed if there are no more errors (this depend on error
	       format).

							*atp-debug-mode-debug* *atp-debug-mode-autodebug'
							*atp-debug* *atp-autodebug*
	* if |t:atp_DebugMode| 	= 'debug' or 'autodebug'
	  :DebugMode debug
	  nmap <LocalLeader><LocalLeader>d
	       After the end of compilation (invoked by the user or
	       autocommand) you will get a message with the return status of
	       the compilation. If the exit code is non zero it will be
	       highlighted with |hl-ErrorMsg|.

	       If you open the error window with |:copen| or with the menu
	       option ToggleDebugMode then it will be automatically closed
	       after first compilation with no errors. Quick fix window is
	       closed in both 'silent' and 'debug' debug modes. This depends
	       on |errorformat| which you can set with |atp-:ErrorFormat|
	       and |atp-:ShowErrors|:
		    ATP test for 'no errors' is 'len(|getqflist()|)'. If the
		    debug mode was 'debug' |t:atp_DebugMode| will fall back to
		    |g:atp_DefaultDebugMode| (by default it is the 'silent'
		    mode).

              The 'autodebug' works similar to 'autosilent' mode.

							*atp-debug-mode-Debug* *atp-debug-mode-autoDebug*
							*atp-Debug* *atp-autoDebug*
	* if |t:atp_DebugMode| 	= 'Debug' or 'autoDebug'
	  :DebugMode Debug
	  nmap <LocalLeader><LocalLeader>D
	       This mode is the same as 'debug' + after compilation ATP jumps
	       to first error.

	       The 'autoDebug' works similar to 'autosilent' mode.

							*atp-debug-mode-verbose*
							*atp-verbose*
							*b:atp_VerboseLatexInteractionMode*
	* if |t:atp_DebugMode| 	= 'verbose'
	       Every compilation which is invoked by the user will be run in
	       verbose mode (this mode is mapped to <F5> key).  In this mode
	       latex '-interaction=' switch is set from the variable
	       |b:atp_VerboseLatexInteractionMode| (the default value is
	       errorstopmode).

	Note: the 'verbose' mode in 'Vim' (in the console) needs to be run,
	when there is no other latex instance running. Now you get a message
	to wait until compilation ends. In future releases, a better solution
	will be worked out. Gui version 'gvim' works better (as it doesn't
	suspend the editor).

	The background compilation is always done in |g:atp_DefaultDebugMode|.
	Unless it is set to 'verbose' in which case 'debug' mode is used. 


	See also |atp-:copen|.

      							*g:atp_ProgressBar*
>
 g:atp_ProgressBar = 1  
<       By default, when using the python compiler you will get progress 
	message in your status line. The number indicates the last page number
	compiled by LaTeX. If by some reason, you want to switch this off, set
	g:atp_ProgressBar to 0 (use |let|).

	You need |g:atp_statusNotif|=1 and |g:atp_statusline|=1 for this
	feature to work (see also |laststatus| on how to activate status line
	in Vim).

	If there are many background processes the number which is shown
	belongs to the oldest process. (|g:atp_ProgressBarValues| is a dictionary
	{ 'pid' : 'pagenr' } - status line shows max of pagenr's).

	Note: the time between you start to compile and when [1] appears in
	the status line is mostly the time when LaTeX is reading all the
	packages loaded in the preamble.

	Limitations ~
	Progress Bar doesn't like when you switch windows while the
	compilation takes time. You might need to use |atp-:Kill| command. 
>
 g:atp_ProgressBarValues
<	This is a dictionary of dictionaries:
	    { 'bufnr' : {dict}, ... }
	Every buffer gets its entry (by |bufnr()|). The {dict} is a dictionary
	which is an empty dictionary {} if compilation is not going on, and
	while compilation it contains the dictionary of PID number and page
	number where the compilator actually is doining its job.

	Note: If you compile and the progress bar starts at page > 1, you can
	use 'let |g:atp_ProgressBarValues|={}' to reset the progress bar. You
	should check if there is any LaTeX process running in the system.
	You can also use the |atp-:Kill| command which will reset the
	progress bar and kill the corresponding processes.

						    	*g:atp_DebugModeQuickFixHeight*
>
 g:atp_DebugModeQuickFixHeight = 8
<	This is the maximal height of |quickfix| window when opened by ATP.

	 						*atp-debug-mode-maps*
	 You can invoke compiler in the 'debug' mode with '|<LocalLeader>|d',
	 '|<LocalLeader>|D' for 'Debug' mode (jump to first error),
	 '|<LocalLeader>|l' uses the default mode.
	 						*g:atp_DefaultDebugMode*
>
 let g:atp_DefaultDebugMode = 'silent'
< 	This is the default debug mode in which background compilation will
	run. It can be set to 'debug', setting it to 'verbose' will have the
	same effect as setting it to 'debug'. ATP will come back to this debug
	mode if compilation ends with exit status 0.

	When compilations ends without errors (i.e. when quick fix list is
	empty for the current error format) |t:atp_DebugMode| falls back to
	|g:atp_DefaultDebugMode|.

							*g:atp_DebugCmdHeight*
							*g:atp_cmdheight*
>
 g:atp_DebugModeCmdHeight = &cmdheight
<       the default cmd height (see |cmdheight|) for the debug mode. 
	ATP will switch to it back and forth if needed. By default it is set
	to |cmdheigh| value (thus unless you set it to sth else you will not
	see the difference). 

	When going out of debug/Debug modes cmdheight is set to
	|g:atp_cmdheight| value (with default value set from 'cmdheight'
	option on startup). 

	Note: if you change |cmdheight| you should also change
	|g:atp_DefaultCmdHeight|, unfortunately vim has not autocommand group
	event to do that automatically.


:DebugMode [debug-mode]					*atp-:DebugMode*
	Command which help to set |t:atp_DebugMode| variable (has completion).
	[debug-mode] is one of "silent", "debug", "Debug", "verbose" (they can
	be suppressed to 's', 'd', 'D' or 'v' (or "si"/"sil"/"sile"/... etc).
	If no argument is given it shows the current debug mode.

	:DebugMode[!] s[ilent]
	nmap <LocalLeader><LocalLeader>s
	:DebugMode[!] autos[ilent]
		It will load error file (|cgetfile|) with bang "!" it will
		open |quickfix| window if there are errors (|cwindow|). If
		|quickfix| window was opened it will be closed.
		Sets |t:atp_DebugMode|='silent' ('autosilent').
	:DebugMode d[ebug]
	nmap <LocalLeader><LocalLeader>d
	:DebugMode[!] autod[ebug]
		It will load error file (|cgetfile|) and open |quickfix|
		window with |:copen|.
		Sets |t:atp_DebugMode|='debug' ('autodebug')
	:DebugMode D[ebug]
	nmap <LocalLeader><LocalLeader>D
	:DebugMode[!] autoD[ebug] 
		It will load error file (|cgetfile|) and open |quickfix|
		window with |:copen|.
		Sets |t:atp_DebugMode|='Debug' ('autoDebug')
	:DebugMode v[erbose]
		Sets |t:atp_DebugMode|='verbose'

	The height of the |quickfix| window will be one more than the length
	of quick fix list (|getqflist()|) but nor more than
	|g:atp_DebugModeQuickFixHeight|.
							
:copen							*atp-:copen*
	Works slightly different than |:copen|. The [height] argument will not
	take effect. Use |:resize| instead. ATP computes the height of the
	QuickFix window, and uses the variable |g:atp_DebugModeQuickFixHeight|
	as an upper bound for QuickFix window height.

							*b:atp_ReloadOnError*
The variable b:atp_ReloadOnError if set to 1 (which is the default) reload the
file even when the exit status of compiler was non zero. If set to 0, then the
file will not be reloaded [actually for viewers other than Xpdf it will not be
copied from the temporary directory, for Xpdf it will be copied but not
reloaded). 

There is also a variable which stores the last command which executed
your tex compiler, see |g:atp_TexCommand|.   

:{runs}TEX[!] [debug_mode]				*atp-:TEX*
map [runs]<LocalLeader>l, map [runs]<LocalLeader>d
	If anyway you want to run TeX yourself but you do not want to see the
	output this is the right tool. This runs TeX in 'nonstopmode'. You can
	specify an argument {runs} which tells how many consecutive runs of
	TeX you need (this is important if you want to compile Table of
	Contents, or index, or the bibliography (see |atp-:Bibtex|)

	Without "!" it copies the aux file only if there are no compilation
	errors, with "!" it updates the aux file even if there were errors.
	This is done to make the labels completion work better, when there are
	errors they often affect the aux file in a way that interferes with
	|atp-:Labels| command. However ATP also makes a copy of aux file with
	extension ._aux - this is for label completion: |atp-completion-label|.

	If b:atp_OpenViewer=1 and there current viewer (b:Viewer) is not
	running on the output file then this function will open a viewer. By
	default b:atp_OpenViewer=0 and this feature is disabled. 

	The command :2TEX will call the compiler two times.

	It is useful when you want to make the outline (using hyperref
	package) of your article in pdf files, the tex file has to be
	'sourced' twice. To make the bibliography you can use |atp-:Bibtex|.

	If {runs} > 5 it will be reduced to 5, to avoid running tex for hundreds
	(or event thousands) of times (what could happen otherwise by
	a mistake giving the range of the command to be the current line
	number).

	The optional argument [debug_mode] has possible values: '', 'silent',
	'debug', 'Debug', 'verbose'. When '' the current debug mode is used
	(|t:atp_DebugMode|). ( [debug_mode] can be suppressed to 's', 'd',
	'D', 'v' or "si"/"sil"/"sile"/... etc.) See the description of
	|atp-debug-mode|.

	\d is mapped to :TEX debug and \l to :TEX (thus it uses your default
	debug mode).

:TEXL [debug_mode]						*atp-:TEXL*
map <LocalLeader>k
	This command compiles the current subfile (L - comes from "local") of
	the project (you have to use subfiles package). 

	This commands also sets 'errorfile' option (using |atp-:TEX| will set
	it back to the main log file).
	
	Note that ATP is coping the project aux file (if present) and using it
	for compilation of subfiles. In this way you get all the labels and
	references. If you add new labels to the subfile then ATP will copy
        the corresponding entries from the subfile aux file to the main aux
        file. However, it will not work if the label (its value) was changed
        or removed. Then you need to compile the project with |atp-:TEX|
        command.

	Note: the advantage of using subfiles package is that you
	can use |atp-:SyncTexL| command for forward searching in the local
	output.


:{runs}DTEX 							*atp-:DTEX*
map [runs]<LocalLeader>d 
	This is equivalent to ':TEX debug'.

:MakeLatex[!]						*atp-:MakeLatex*
	With one command you can make your whole document: cross references,
	bibliography (with or without bibtex), index, table of contents, table
	of figures, table of theorems ([ntheorem package]), table of
	algorithms. ':MakeLatex!' should be used when an entry in the
	bibliography was deleted (when 'bibtex' is involved this is when you
	delete last citation command of a bib entry).

	If aux or log files are loaded in a buffer then they will be deleted
	- this is a requirement of vimgrep internal grep command (other wise
	vimgrep will search in the buffer not the hard disk version and they
	may differ). 

	Returns with error message if log contains '! Emergency stop.'

	If |g:atp_Compiler| = 'python' it uses the python script to compile
	document, if |g:atp_Compiler| = 'bash' it uses a bash command (UNIX
	only).

:Bibtex[!] [debug_mode]					*atp-:Bibtex*
map <LocalLeader>b
    With BANG "!":
	This function will call bibtex to produce the bibliography file
	(.bbl). If in |b:atp_OutDir| there is no 'aux' file it first calls tex
	compiler. After the 'bbl' file is produced two consecutive runs of tex
	compiler are called to make the bibliography.

	If you specify any value to the [debug_mode] option (for the values
	see |atp-:TEX|) In verbose mode (only the last time tex compiler will
	run in errorstop mode and echoed to the console). This gives you the
	chance to see the output of bibtex command (it will be also printed
	when latex ends). 
	
	If bibtex returns with non zero exit code, latex will not be run
	afterwards. 
	
    Without BANG "!"
	If you want to just run bibtex use :Bibtex without
	bang.

	The command |atp-:Bibtex|  will :call Bibtex(), while :Bibtex v
	(and :Bibtex [debug_mode]) will :call Bibtex(1)

	The bang "!" is used in the same way as for |atp-:TEX| command.

	For the description of optional argument [debug_mode] see |atp-:TEX|.


							*g:atp_raw_bibinputs*
    Tex is looking for the date base files in the path: `kpsewhich -show-path
    bib`. The variable g:atp_bibinputs contains these directories separated by
    commas. If atp cannot find your bib file, tex also won't be able. 
							*g:atp_raw_texinputs*
    Similarly this variable stores all of path reported by `kpsewhich
    -show-path tex`.
							*g:atp_bibinputs*
    This is a list of directories as g:atp_raw_bibinputs with appended '**'
    see ':h file-searching'.
							*g:atp_texinputs*
    This is a list of directories as g:atp_raw_texinputs with appended '**'
    see ':h file-searching'.

    Note: The above four variables might be added to
    |g:atp_ProjectGlobalVariables|. ATP will start faster, but remember to
    unlet them and restart vim when you change your TeX distribution, so that
    ATP will rebuild them.

							*atp-:Kill*
:Kill							
	Kill python scripts running (b:atp_PythonPIDs) and all pids in
	|b:atp_LatexPIDs|. This only works with |g:atp_Compiler|="python".

:PID 							*atp-:PID*
	Prints PIDs of all running instances of |b:atp_TexCompiler|.


:Compiler {compiler-program}				*atp-:Compiler*
	Command which help to set |b:atp_TexCompiler| variable (with
	completion).

							*atp-:SetOutDir*
:SetOutDir					
	This is a command which sets the |b:atp_OutDir| variable and the
	|'errorfile'| option.  See |b:atp_OutDir| for the default value.

							*atp-:Latexmk*
:Latexmk[!]
	Compile with latexmk in background. 
	With bang "!": Force compilation with latexmk in background.
	See |g:LatexBox_latexmk_options|.

							*atp-:LatexmkClean*
:LatexmkClean[!]
	Clean temporary output from LaTeX. 
	With bang "!": Clean temporary output from LaTeX.

							*atp-:LatexmkStop*
:LatexmkStop
	Stop latexmk if it is running.

							*atp-:LatexmkStatus*
:LatexmkStatus[!]
	Show the running status of latexmk for the current buffer. 
	With bang "!": show the running status of latexmk for all buffers with
	process group ID's.

:ShowErrors [flag]					*atp-:ShowErrors*
nmap <LocalLeader>e					/for other maps see |atp-:ShowErrors-maps|/
	This command shows error/warning messages. It sets the |'errorformat'|
	variable accordingly to the optional [flag] argument, which is a word
	made of letters:
>
		e		- include errors
		w		- include all warning messages
					(with g:atp_ParseLog, font warning messages are excluded)
		r		- include all reference warnings
		c		- include all citations warnings
		f		- include all font warnings
		fi		- include font info massages
		F		- show files listed in the log
				    (messages which start with 'File: ')
				    shows the files loaded by tex
				    for example fd files that LaTeX is using
		p		- show package info messages (g:atp_ParseLog only)
		P		- show packages loaded by tex 
				    (messages which start with 'Package: ')
		h		- show 'Overfull \hbox' and 'Underfull \hbox' messages (g:atp_ParseLog only)
		o		- open the log file in a new buffer (split).
		all		- all excluding f,fi,F,p,P
		All		- with g:atp_ParseLog:  show all the above,
				  with !g:atp_ParseLog: show whole log file.
<
	If none flag is given |g:atp_DefaultErrorFormat| value is used.  If
	'o' flag is used the split buffer with log message has a map 'q' to
	':bd'.  Example: >
		:ShowErrors rc
<	will show all reference and citation warnings.

	Note: this command works in quickfix window. It will change
	errorformat but will not reload quickfix list. Better use
	|atp-:ErrorFormat| instead.

							*atp-:Cgetfile*
:Cgetfile	
	This works like |:cgetfile| command, but also filters errors from
	quick fix list which are not recognised by |errorformat| (it is done
	by |atp-:ShowErrors|). This is only useful with |g:atp_ParseLog|=1.
	Otherwise it acts like |:cgetfile|. If you use cmdalias plugin
	(vimscript 746) you can alias this command to cg (|:cg|) in |atprc|
	file.

							*g:atp_ParseLog*
g:atp_ParseLog = 1
	If |g:atp_ParseLog| is 1 (|g:atp_Compiler|="python"), then ATP will
	parse the log file. So that |quickfix| will show you corrent file
	names for the errors. This is particullary usefull for project 
	files. The new log file is written with an extension '_log'.

							*g:atp_DefaultErrorFormat*
g:atp_DefaultErrorFormat = 'erc' 
    The value is the  same as argument to |atp-:ShowErrors| and
    |atp-:ErrorFormat|. This is the default argument for these commands when
    they are used without any argument. Also corresponding 'errorformat' is
    set up at startup.
						 
							*b:atp_ErrorFormat*
b:atp_ErrorFormat = 'ecw'
	This variable stores the current format of errors. It is a word with
	letters given in [flag] argument to |atp-:ShowErrors|. You can set it
	with |atp-:ErrorFormat| command. It is used by serveral ATP functions,
	for example call back feature checks if there are errors looking into
	Quick Fix list (with |getqflist()|), which will depend on the variable
	|b:atp_ErrorFormat|.
	    

ShowErrors maps:					*atp-:ShowErrors-maps* 

<LocalLeader>e		view errors with current |b:atp_ErrorFormat|	(:ShowErrors)
<F6>+e			to see all errors 			      (:ShowErrors e)
<F6>+w			to see all warnings			      (:ShowErrors w)
<F6>+r			to see warnings coming			      (:ShowErrors rc) 
			from references or citations  
<F6>+f			to see font warnings 			      (:ShowErrors f)

This is not a texloganalyzer mapping but it is a good place to mention it:
<F6>+l			to open log file in a new split window
			this is a mapping to the |atp-:OpenLog|.

:ErrorFormat {flag} 					*atp-:ErrorFormat*
	This command has the same syntax as |atp-:ShowErrors|. It sets the
	|b:atp_ErrorFormat| variable and vim option |'erroformat'|, and the
	rereads the log file with |cgetfile|. If {flag} is not given it only
	shows the current value of |b:atp_ErrorFormat|.  The variable
	|b:atp_ErrorFormat| is also set when you use the command
	|atp-:ShowErrors|.

	As an argument you may use +{flag} and -{flag} then {flag} will be
	added/removed from |b:atp_ErrorFormat|, example: >
		:ErrorFormat +w
		:ErrorFormat +w-f
		:ErrorFormat -F+e
<	will add 'w' to |b:atp_ErrorFormat|.		
	Note: this command works in quickfix window as well.

							*atp-:SetErrorFile*
:SetErrorFile					
	If you change |b:atp_OutDir| variable and you want to update the
	|'errorfile'| option use this command. It will show you the value to
	which |'errorfile'| was set. 

:ShowErrors o						*atp-:OpenLog*
:OpenLog, map <F6>l, imap <F6>l
	Opens log file in a new split window with two options (which are set
	locally): 'ruler', 'nospell', and a map 'q' to ':bd'.	

	You can also use the command ':Explore' to see log, aux, ... files
	(which is a part of 'netrw' Vim plugin).


In the log file there are some special tools to syncronize the tex source file
and the Viewer (currently only Xpdf is supported) with log file:
|atp-:SyncTex| and |atp-:SyncXpdfLog|) These tools can sync tex file/Xpdf
automatically using autocommand group |CursorMoved|.

							*atp-:SyncTex-(log_file)*
:SyncTex[!]	(inside log file)
:nmap <LocalLeader>f, nmap <Enter>
	If you open log file with ':ShowErrors o' command then you can use
	this command to move to the place in the source code where the error
	occurs. It works with project files and also can go to error which
	appear in a declared package. It will go to the first error line
	declared in the log file below the cursor position (more precisely, to
	first line which matches '^l\.\d\+\|on input line\|at lines' will be used).

	With bang [!] it opens new window if the file with error is not shown
	in the current tab page. Without bang it opens the file in the window
	where ':ShowErrors o' was used.
							*g:atp_LogSync*
	If you set |g:atp_LogSync|=1 (the default value is 0) then the source
	file will be syncronize with the log file via autocommand (with
	|CursorMoved|). This sets 'cursorline' option to indicate the
	corresponding line in the source file. When the log buffer becomes
	hidden this option should be unset.
							*atp-:LogSync*
	To set |g:atp_LogSync| you can use |atp-:Sync| command. |atp-:Sync|
	will toggle the value, ':Sync on' will set it to 1 and ':Sync off'
	will set it 
	to 0.

	If you set g:atp_developer = 1 this command will also go to files
	under texmf tree (packages and classes).

							*atp-:SyncXpdf*
							*g:atp_SyncXpdfLog*
:SyncXpdf
	If you set g:atp_SyncXpdfLog = 1 (the default value is 0) and you use
	Xpdf as a viewer it will be synchronised with the log file (with
	autocommand group |CursorMoved|). You can also use the command
	:SyncXpdf or :Xpdf in the log buffer which does the same.

:View[!] 						*atp-:View*
map <LocalLeader>v, map <F3>, imap <F3>  
	You would like to see what you are editing use this function. It will
	use the program defined in the variable b:atp_Viewer. See |b:atp_Viewer|,
	|g:atp_XpdfServer|, |atp-xpdfOptions|. When there is no output file it will run
	TeX and open the file. Read more about particular viewers
	(inverse/reverse searching) in |atp-viewers|. 

	With bang (and <F3> maps) opens viewer at the cursor position in vim
	(forward search). This will only work for viewers that support forward
	searching (xpdf, xdvi, okular, skim).

							*g:atp_OpenAndSyncSleepTime*
let |g:atp_OpenAndSyncSleepTime|="500m"
	Give 500 milliseconds for the viewer to read the file, before
	|atp-:View|! and |atp-:ViewL|! commands will do a forward search.

:ViewL[!]						*atp-:ViewL*
map <LocalLeader>V, map <S-F3>, imap <S-F3>  
	With this command you can view the subfile comiled by |atp-:TEXL|
	command (or with |b:atp_autex|=2). "L" comes from "local".

	Bang and [i]map <S-F3> works as in |atp-:View|! command (and its <F3>
	map).

:SyncTex[!]						*atp-:SyncTex* *atp-\f*
map <LocalLeader>f, map <S-LeftMouse>
	Which makes an forward search (vim->Viewer). As for now ATP supports Okular,
	Xpdf and Xdvi with this feature (Evince is not yet supported).

	With bang |atp-:SyncTex| will not check if the viewer is running.

	Note: you can also set reverse search for Okular and Xdvi, see
	|atp-Viewers-Okular| and |atp-Viewers-Xdvi| for an instruction how to
	do that. Xpdf doesn't support reverse searching.

							*atp-:SyncTex_Xpdf-hack*
	Note: there is a bug in Xpdf, one cannot sent commands to Xpdf to
	quickly. If the |atp-:SyncTex| command only updates the page, but
	doesn't shift it then you can try to set g:atp_XpdfSleepTime variable
	to something higher than the default 0.1 (this is sleep time between
	sending commands to Xpdf in seconds)

	When the output file or the synctex file (.synctex.gz) doesn't exists
	then first it will be generated. It can also open the document if it
	is not yet opened.

	Read |atp-:SyncTex_with_Okular| if you use Okular.

:SyncTexL[!]						*atp-:SyncTexL* *atp-\F*
map <LocalLeader>F
	Forward search from the subfile to its output (as compiled with
	|atp-:TEXL| or |b:atp_autex|=2).

	With bang |atp-:SyncTexL| will not check if the viewer is running.



:Viewer {viewer-program}				 *atp-:Viewer*
    Command which help to set b:atp_Viewer variable (with nice completion).

:SetXdvi						*atp-:SetXdvi*
	This command sets the options for xdvi viewer, which enables inverse
	and reverse searching. You can use the command |atp-:SyncTex| for
	forward searches (Vim->Xdvi) >
		:SyncTex	(although dvi is using srcspecials rather than synctex)
		map <LocalLeader>f
		nmap <S-LeftMouse>
<	For inverse searching hold CTRL and press click left mouse button on
	the text in xdvi viewer. It sets: >
	    let b:atp_TexOptions="-src-specials"
<	and also other variable to enable reverse searching (Xdvi->Vim) see
	more |atp-viewers-Xdvi|.

	This command sets |g:atp_xdviOptions| variable, but do not overrides
	your settings if you defined '-editor' and '-watchfile' switches (it
	defines only these two, watch file makes xdvi reload the file every
	given interval)

:SetXpdf						*atp-:SetXpdf*
:SetOkular						*atp-SetOkular*
	This command sets options for Xpdf viewer. Xpdf supports forward
	searching (vim->Xpdf) with command: |atp-:SyncTex|. It sets >
	    let b:atp_TexOptions="-synctex=1"
< 	Thus it enables the forward searching (the above is the default 
	value for ATP, but it will change when you use |atp-:SetXdvi| which
	uses "-src-specials".

	It reads the Xpdf viewer options from the variables
	|b:atp_xpdfOptions| and g:atp_xpdfOptions. Similarly for Okular.
						
							*atp-:PdfFonts*
:PdfFonts
nmap <F6>g
	Runs external program pdffonts on pdf output file.

:BibSearch /{pattern}/ [flag]				see |atp-:BibSearch|
	This function finds bib entries in bib files defined in your tex file
	and in the variable |b:atp_BibFiles|, which match the
	[pattern] (a Vim regular expression). The output is configurable by
	the [flag] argument, see |atp-bibflags|. By default the pattern is
	case insensitive.

							*atp-:AMSRef*
:AMSRef[!] {bibdata}  
    A command to get bib data from AMSRef:
		    http://www.ams.org/mathscinet-mref 
    The bib data will be appended to bibliography of the current document. If
    there are many bib files will get a choice which one to use. This command
    is also available in bib files.  Without bang, i.e. "!", it writes and
    closes the bib buffer with it will leave you in unsaved bib file buffer.
    You will be also asked for the bib key, the default choice is to use the
    AMS bib key. 

    							*g:atp_bibrefRegister*
    This command also works when you use \begin{bibliography} environment. But
    the default is to use a bib file.  The obtained bibliographic reference is
    copied to the register |g:atp_bibrefRegister| (the default is "0" so you can
    paste it using Vim command 'p'). In addition, it is stored in the variable
    g:atp_bibref.

:BibYank						see |atp-:BibYank|, |atp-:BibPaste|
map [count]c, [count]y, 
:BibPaste
map [count]p, [count]P
	This commands are defined in the buffer with results of
	|atp-:BibSearch| command. It is mapped to '[count]y', '[count]c',
	'[count]p' and '[count]P' and let you copy the bib entry key to
	a register (see |atp-:BibYank|) or directly to the last opened buffer.

:FindBibFiles						*atp-:FindBibFiles*
	This updates the variables s:bibfiles, s:allbibfiles,
	s:notreadablebibfiles. Finds all bib files defined in all
	'\bibliography' commands. For more about the above variables read
	|atp-variables-bib|. The command |atp-:FindBibFiles| finds bib
	files in the current buffer. 

	If a readable bib file was not found under one of path listed in of
	g:atp_bibinputs variable (see |g:atp_bibinputs|) it is classified
	as not readable.  
							
:GotoFile[!]						*atp-:GotoFile*
:Edit[!]				 		*atp-:Edit* *atp-gf*
nmap gf
	This command finds input files under b:atp_MainFile (it is recursive).
	The nmap 'gf' checks first if there is a file under the cursor. If
	there is no file under the cursor it list all input files. Input file
	is one introduced in the source file with \input{<file>}, \input
	<file> \include{<file>}. The current file is now shown with highlight
	group: |hl-WarningMsg|. 

	This command uses kpsewhich to find in which path to find input files.
	Actually the path variables: |g:atp_texinputs| for input files and
	|g:atp_bibinputs| for bib files are used.

	The bibliographic declared are also listed. The command searches for
	them in any directory listed in g:atp_bibinputs (see
	|g:atp_bibinputs|).

	If g:atp_developer = 1 (default 0) then the map 'gf' can also open
	package files and document class files, but only when using 'gf' over
	\usepackage, \documentclass, and \RequirePackage commands.

	With bang "!" this command regenerates tree of files (this is
	important only in files with input lines), without it uses cached
	values (if they exist).

	The current file is now shown with highlight group: |hl-WarningMsg|. 

:KpsewhichEdit {file}					*atp-:KpsewhichEdit*
	Find {file} using kpsewhich and edit it. For example >
	    :KpsewhichEdit amsmath.sty
<
							*atp-:TexDoc*
:TexDoc
map <F1>, imap <F1>
	Then you have to type what you are looking for and press enter. The
	option 'keywordprg' is set to 'texdoc -m', i.e when your cursor is
	over a package name and you press 'K' key then you should see the
	package document file (if it is named after the package).

	Without any argument it will open "g:atp_TeXdocDefault", by default it
	is equal to "-a lshort", i.e. "The not so short introduction to LaTeX
	2e" by Tobias Oetiker. You can change the default for something that
	you use more often, for example you can set it to "-a faq", i.e. 'The
	UK TeX FAQ' (or even to "-a lshort faq" if you want them both :). 

							*atp-:TexDef*
:TexDef[!] {args}
	This command is an interface to the texdef program. Use ':TexDef --help'
	to see the help message. |atp-:TexDef| command automatically sets the
	--tex switch (using |filetype|). If run with bang [!] a comma
	separeted list of packages of the current tex file will be appended to
	the texdef command (using --package switch).
	

							*atp-:InputFiles*
:InputFiles				
	List input files of the current project. It also updates the
	|b:ListOfFiles| and |b:TreeOfFiles| variables to the current values.

	The variable *g:atp_inputfile_pattern* is used as a pattern to find
	input files. If you use 'biblatex' you do not need to put any pattern
	matching bibliographies (\addbibresource, \bibliography, ...), ATP has
	special way of dealing with them which is faster. If you use 'subfile'
	package ATP will add \\subfile pattern.

							*atp-:Open*
							*g:atp_LibraryPath*
:Open[!] [pattern] 
	If you configure g:atp_LibraryPath, this function will find files
	matching [pattern] under g:atp_LibraryPath and let them open with
	a program defined in >
		g:atp_OpenTypeDict
<	The g:atp_LibraryPath is a comma-separated list of directory names.
	You should use wild cards '**' and '*' as in |globpath()|, if you want
	to include subdirectories, etc. For example >
	    let g:atp_LibraryPath=$HOME."/**"
<	will search for files under your $HOME directory. The default value of
	g:atp_OpenTypeDict is: >
	    let g:atp_OpenTypeDict = { 
		\ "pdf" 	: "xpdf",		"ps" 	: "evince",
		\ "djvu" 	: "djview",		"txt" 	: "split" ,
		\ "tex"		: "edit",		"dvi"	: "xdvi -s 5" }
<	The values of g:atp_OpenTypeDict should be a program to open the file,
	or one of 'tabe', 'split', 'edit', (if 'vim' is specified, then 'tabe'
	will be used). The cat program is also supported.

	Found files (all not just matching ones) are stored in the variable
	g:atp_Library. It is set by |globpath()| on g:atp_LibraryPath and then
	filtered, only files which extensions are given in g:atp_OpenTypeDict
	will be stored. This variable is restored by the global project script.
	You can use {bang} "!" to regenerate the library if it has changed.
	This is particularly useful as by default ATP remembers g:atp_Library in
	the common project script (see |atp-ProjectScript|).

							*atp-:Dictionary*
:Dictionary {word}
map =d
	This is an interface to http://www.impan.pl/Dictionary/. Type a [word]
	and you will get quotes from mathematical articles or books written by
	native speakers of English. The command has a completion for words
	List of words is hard coded in ATP (it is too slow to get it), since the
	dictionary evolves it might contain new entries (note: if this is the
	case, please inform me).

	The map takes the |<cword>| under the cursor as an argument.

:Delete[!]						*atp-:Delete*
map <F6>d
	Deletes all files which extension belongs to g:atp_tex_extensions in
	the directory |b:atp_OutDir|. By default |g:atp_tex_extensions| does
	not contain 'tex', 'pdf', 'dvi' so none of your important files will
	be deleted. When the command is used without bang the extensions
	from |g:atp_DeleteWithBang| are removed from |g:atp_tex_extensions|.
	The default value of |g:atp_DeleteWithBang| contains for example
	'synctex.gz' extensions, thus it won't be removed by :Delete (without
	bang "!").
							*g:atp_delete_output*
	If you set |g:atp_delete_output|=1 the function will delete also the
	current output file (but not any other!) and 'synctex.gz' file.

							*g:atp_DeleteWithBang*
>
 g:atp_DeleteWithBang = ['synctex.gz', 'tex.project.vim']
<	This is list of extensions which will not be removed when
	|atp-:Delete| is run without bang. You do not need to add "pdf" or
	"dvi", extensions.

							*atp-:SshPrint*
:SshPrint [lpr_options]
	It will run 'lpr' command and append to it the options defined in the
	variable 'g:printeroptions' + options given in the second argument. It
	prints the pdf or dvi depending on the value of |b:atp_TexCompiler|.
							*g:atp_ssh*
	If you specify the variable 'g:atp_ssh=<user>@<host>' it will print
	via ssh on the <host> using the [lpr_options] passed to the lpr
	command. The command ':SshPrint' has a completion set for the printers
	available on your local system or in the host. You do not have to
	escape white spaces.
	
	The command has completion for the names of printers (also remote
	printers) and also other lpr options and its values, press <Tab> to
	cycle through printers, or type first letters of the printers name and
	press <Tab> to complete it.

							*atp-:Lpr*
:Lpr [lpr_options]					
	It prints using the lpr command on a local printer. The syntax and
	completion are the same as for |atp-:SshPrint|.

							*atp-:Lpstat*
:Lpstat
	Sends "lpstat -l" remotely (using the |g:atp_ssh| value) or locally and
	echoes the output.

							*atp-:ListPrinters*
:ListPrinters
	List printers available on the host |g:atp_ssh|.

							*atp-:Wrap*
:Wrap [beginWrapper] [endWrapper] [cursor_pos] [new_lines]

	Puts selected text between [beginWrapper] and [endWrapper]. Also sets
	the cursor position according to the [cursor_pos]. Possible values
	are: a number -- indicates the character offset from beginning of
	[beginWrapper]; or 'end' put the cursor at the end of [endWrapper] or
	'begin' leave the cursor at the beginning (to be precise at the end of
	the starting wrapper).  The default [beginWrapper] is '{' and
	[endWrapper] is '}'.  The last argument [new_lines] has two values 0/1
	(default is 0): if 1 then the [beginWrapper] and [endWrapper] are put
	in separate lines (the begin line and end line are split), this is
	useful for putting text into an environment \begin{}:\end{}. 

	See |<f-args>| to know how to pass arguments. (They are separated with
	spaces, white spaces in arguments should be escaped with backslash
	'\'.)

	For the predefined maps which use WrapSelection see below
	|atp-maps-WrapSelection| or use |atp-:HelpVMaps|.

							*atp-:Unwrap*
:Unwrap	
nmap <LocalLeader>u
	If cursor is standing over a bracket it will remove both matching
	brackets together with \left:\right, \bigl:\bigr, ... sizes. This
	works for: (:), {:}, [:], \{:\}, \[:\] and \(:\).

							*atp-:IWrap*
:IWrap {mathWrapperPair}, {textWrapperPair}, [cursor_pos], [new_lines]

	Puts the selected text inside {mathWrapperPair} if the cursor stands
	in mathematics otherwise inside {textWrapperPair}.  {mathWrapperPair}
	{textWrapperPair} are Vim lists of length at least 1, the first
	wrapper is the opening and the second is the closing one (if not given
	the default '}' is used. The other arguments are as for
	|atp-:Wrap|. If the opening leader in is not given then this
	command is not wrapping the text (see below for the suggested map
	'\tx').

	The command arguments should be separated with commas and quoted
	separately (see |<args>|).

	For the predefined maps which use |atp-:Wrap| see below
	|atp-maps-InteligentWrapSelection| or use |atp-:HelpVMaps|.

	See section |atp-vmap-WrapSelection| on predefined set of vmaps.

	You can also use a wrapper which was yanked into register 'a': >
		:Wrap @a
<  	This will work not only in visual mode. It will operate on last
	selected text. So if you accidentally lost the selection you can still
	use this command (but not the maps)!

							*atp-:TexAlign*
:TexAlign[!]
map <LocalLeader>a 
	This is a wrapper around Align command of the great AutoAlign Vim plugin:
	    http://www.vim.org/scripts/script.php?script_id=884. 
	This command sets correct align options and aligns the environment.
	The following LaTeX environments are supported: >
	    equation, align, alignat, flalign, displaymath and tabular
<	Equation, align, alignat, flalign and displaymath are checked using
	syntax, tabular environment is checked using searchpair() function,
	the |g:atp_completion_limits|[2] applies.

	The command :Align (and thus also :TexAlign) are using ATP_strlen
	function to measure the string length. ATP sets
	g:Align_xstrlen="ATP_strlen" if 'conceallevel' option is >0. If
	'conceallevel' is reset to 0 ATP_strlen behaves like
	g:Align_xstrlen=2.

	With bang "!", |atp-:TexAlign| will join lines which do not ends with
	'\\'. If *g:atp_TexAlign_join_lines* =1 then the map <LocalLeader>a
	will use the bang.
    							*atp-:LatexTags*
							*atp-:Tags*
:Tags[!]
:LatexTags[!]
    Make a tag file with a python script included in ATP. It also scans aux
    file for associated numbers to labels which then are used as tags. If you
    declare hyperref package in the preambule also \hyperref{}{} commands are
    matched for tags as well. 
    |atp-:Tags| command will be defined only if you do not define it yourself. 

    Natbib as well as biblatex commands are supported (with exception of
    \cites, ... biblatex commands).

    With bang the bibtags for \cite commands are not made. If you use more
    than one bibliography file searching to which of them it belongs might
    take some time. If this is the case and you do not want this kind of tags
    you can make the tag file faster.

    Note: you might need to adjust 'iskeyword' Vim option. ATP is adding
    |g:atp_separator| to 'iskeyword' if |g:atp_no_separator| is 0.

    Note!:In Vim 'iskeyword' by default contains '_'. It is disabled by the
    standard tex syntax file (you do not want to include _ from _{} LaTeX
    construct into 'w' motion). So it is better to avoid it in label names, so
    that |CTRL-]| works well. If you need to add it use:
	au FileType set iskeyword+=_
    (this will not work with setlocal).

    Note: the python script is sourced in the background. When the script
    finishes it will let you know. The tag file is not accessible until the
    script finishes.

    Check out |tag-and-searches| how to use tags.

    :LatexTags command is only defined if there was :Tags command defined.

:TOC[!] 						*atp-:TOC*
nmap <LocalLeader>t
	Shows Table of Contents of your document. It do not yet support the
	starred version of chapter, section,... . 

	The optional argument bang controls if the table of contents data base
	must be generated: by default map <LocalLeader>t doesn't regenerate
	the toc data base (unless if it doesn't exist), :TOC command
	regenerate the data base, :TOC! not.

	See |atp-toc-window| for commands and maps defined in the toc window.

	|atp-:TOC| supports many edited files. The variable t:atp_toc_buflist
	is a list of project names (|b:atp_MainFile|) which are shown in ToC. 
	Use |atp-:RemoveFromToC| to remove a project from ToC. 

	If you have in your buffer list two files a.tex and b.tex this command
	will produce table of contents of both of them. If you have just one
	opened window (excluding the ToC window) then pressing <space>,
	<enter>, p and _ will take you to the right buffer (which will be read
	if is unloaded or hidden). If you split a window then <space>,
	<enter>, p, _ will take you to the window from which you are coming.
	However, if you have two windows with two different buffers loaded
	they will act on the window with the matching buffer name.

	The variable t:toc_window_width sets the width of table of contents
	window. By default t:toc_window_width=30. You can set a global
	variable g:toc_window_width to override the default value.

							*atp-:RemoveFromToC*
:RemoveFromToC {name}
	Remove the project with main file {name} from ToC. There is
	a completion for {name}s.

							*atp-:CTOC*
:CTOC	
	This function returns the name of the currently edited chapter/
	section/subsection/subsubsection. Use ':echo CTOC()' or just ':CTOC' to
	see the returned value. If you added a section unit the function will
	not update the database, run ':TOC' to do that (map <LocalLeader>t).

:Labels[!]						*atp-:Labels*
map <LocalLeader>L 
	Shows labels defined in your file. You can also use the commands and
	mappings described in |atp-toc-window|.

	If you forget what are these mappings, write ':map <buffer>' in the
	TOC or LABELS window, or move to the end of the LABELS window to see
	a short help message.

	The key 's' shows the context of the label under the cursor (your
	current window splits).

	The variable t:labels_window_width sets the width of labels window. By
	default t:labels_window_width=30. You can set a global
	variable g:labels_window_width to override the default value.

	Without bang "!" the labels data base will not be generated.
	Difference of \t and \L  is that \L regenerates the database (which is
	quite fast).

	Note: in memoir class you will not see labels type (in square
	brackets).

  							*atp-:GotoLabel*
:GotoLabel[!] {pattern} 
	The command does the obvious thing. The {pattern} matches against the
	label or label value (as appears in output file). When matching the
	label value '^' is added at the beginning of pattern. With bang it
	doesn't regenerate the labels dictionary. It works with project files.
	It has completion.  If pattern matches many labels they all are listed
	with some useful info: label value, label and the file where it was
	defined (only in projects). Examples: >
	    :GotoLabel 1.2
	    :GotoLabel ^thm:
<       Note: there is |atp-:Tags| command which makes the tag file, and you
	can use vim |tags| commands.

	Note: You can also use a tag file and vim |tags| commands, see
	|atp-:Tags|.

							*atp-:GotoNamedDest*
							{only in Xpdf}
:GotoNamedDest <destination_name>
	Using '\hypertarget{<destination_name>}{<text>}' from hyperref package
	you can insert into PDF named destinations. This command will set the
	position of PDF file in Xpdf to this destination. There is
	a completion for destination names. This command solely works with
	Xpdf. Using: >
	    :%s/\\label{\([^}]*\)}/\hypertarget{\1}{}/gc
<       you can turned labels into named destinations.


							*atp-:F*
:[count]F {arg}							
	Go (forward) to {arg}, {arg} might be: part, section, subsection,
	subsubsection, and defined environment. You can use command completion
	which uses all the locally defined environments.

							*atp-:B*
:[count]B {arg}
	Go (backward) to {arg}, like above |atp-:F|.


							*atp-:NEnv* *atp->e*
:NEnv {environment}
:[count]F {environment}
map [count]>e
	Move to next environment, for example ':NEnv definition'. Completion
	is set, which finds environments defined in current tex source file.
	This function omits environments in comment lines.

							*atp->m* *atp->M*
	{environment} can be also math or displayedmath. For convenience
	there are maps: }m and }M respectively.

	If g:atp_mapNn is set to one (see |atp-:ToggleNn|) then this command
	is using |atp-:S|.

							*atp-:PEnv* *atp-<e*
:PEnv {environment}
[count]:B {environment}
map [count]<e
	Move to previous environment, for example ':NEnv definition'. Completion
	is set, which finds environments defined in current tex source file.
	This function omits environments in comment lines.

 							*atp->E* *atp-<E*
nmap [count]>E
nmap [count]<E
	There are two more nice map >E which is something like %>e, i.e. jump
	over the current environment and go to next one. The reverse <E is
	also implemented, thought it is not simply <e%. They do not support
	count (yet), and actually count breaks them. If you want to add |zz|,
	(|zt| or |zb|) after >E you can put this in your |atprc| file:
	    map <buffer> <silent> >E	<Plug>JumptoNextEnvironmentzz
	    map <buffer> <silent> <E	<Plug>JumptoPreviousEnvironmentzz

	|atp--S|, |atp--s|, |atp--c|, |atp--p| new maps for |atp-:SSec|,
	|atp-:Sec|, |atp-:Chap| and |atp-:Part|. They also works relatively to
	the current unit (section/chapter/part), i.e. 2]s will jump to second
	section of the current chapter.

							*atp->f* *atp-<f*
							*atp->F* *atp-<F*
nmap [count]>f [count]>F
nmap [count]<f [count]<F
	These two maps are only valid in beamer. They goto next/previous
	frame. >F and <F are using |zt| command.
    	
						


							*atp-<m* *atp-<M*
	{environment} can be also math or displayedmath. For convenience
	there are maps: {m and {M respectively.

	If g:atp_mapNn is set to one (see |atp-:ToggleNn|) then this command
	is using |atp-:S|.

							*atp-:NextSection*
							*atp-:NPart*	*atp->p*
							*atp-:NChap*	*atp->c*
							*atp-:NSec*	*atp->s*
							*atp-:NSSec*	*atp->S*
							*atp-:NSSSec*
:NPart[!], :NChap[!], :NSec[!], :NSSec[!], :NSSSec[!] [title_pattern]
[count]:F {section}
 map >p,  map >c,  map >s,  map >S
vmap >p, vmap >c, vmap >s, vmap >S

	Go to next part/chapter/section/subsection/subsubsection which title
	matches optionally given [title_pattern]. With bang "!" the command
	doesn't skip commented sections. Maps skip them. The search will wrap
	around the end of a file if 'wrapscan' is set.

	The {section} argument for :F is one off:
	    part/chapter/section/subsection/subsubsection.

	Map  		Command			Meaning
	>p		:NPart			go to next part
	>c		:NChap			go to next chapter
	>s		:NSec			go to next section	
	>S		:NSSec			go to next subsection

							*g:atp_map_forward_motion_leader*
	You can set the leader '>' using |g:atp_map_forward_motion_leader|
	variable.

	Note: If you leave the default value of |g:atp_forward_motion_leader|
	then ATP remaps |>>| to >> and also |v_>| to >>. |>| is working and is
	not touched by ATP. If you have |'timeout'| set then the map is
	executed faster, if you use |'notimeout'| this workaround it makes
	these operators work.

	Note: If you set |g:atp_forward_motion_leader|="}" then ATP remaps |}|
	operator to }}

	Note: the maps work in visual mode and operator pending mode ('d\ns'
	will delete till the end of the section). You can use |n| and |N| Vim
	normal commands (also in visual mode) to go further. 

	In visual mode these maps go to end of current section or, if already
	at the end of section, end of next section. 

	[title_pattern] is the pattern which will match for the pattern, it
	should start with '.*' when you want to match somewhere in a middle of
	the title. 
	
	These commands (and maps) use Vim |search()| function or |atp-:S| command
	depending on the value of |g:atp_mapNn| (see |atp-:ToggleNn|, when
	g:atp_mapNn=1 the |atp-:S| command is used). You can set the value
	of |g:atp_mapNn| using the command |atp-:ToggleNn|. If 'wrapscan' is
	set and g:atp_mapNn=1 the search will wrap around the end of the
	project (not the end of the current buffer).

	You can unmap these keys and use <Plug>GotoNextSubSection,
	<Plug>GotoNextSection, <Plug>GotoNextChapter, <Plug>GotoNextPart to
	define new maps.


							*atp-:PrevSection*
							*atp-:PPart*	*atp-<p*
							*atp-:PChap*	*atp-<c*
							*atp-:PSec*     *atp-<s*
							*atp-:PSSec*	*atp-<S*
							*atp-:PSSSec*
:PPart[!], :PChap[!], :PSec[!], :PSSec[!], :PSSSec[!] [title_pattern]
[count]:B {section}
 map <p,  map <c,  map <s,  map <S
vmap <p, vmap <c, vmap <s, vmap <S

	Go to previous part/chapter/section/subsection/subsubsection which
	title matches [title_pattern] (an optional argument). With bang "!"
	the command doesn't skip commented sections. Maps skip them. The
	search will wrap around the beginning of a file if 'wrapscan' is set.

							*g:atp_map_backward_motion_leader*
	You can set the leader '<' using |g:atp_map_backward_motion_leader|
	variable.

	The {section} argument for :B is one off:
	    part/chapter/section/subsection/subsubsection.

	For description of arguments read |atp-:NextSection| just above.

	Map  		Command			Meaning
	<p		:PPart			go to previous part
	<c		:PChap			go to previous chapter
	<s		:PSec			go to previous section	
	<S		:PSSec			go to previous subsection

	These commands (and maps) use Vim |search()| function or |atp-:S|
	command depending on the value of |g:atp_mapNn| (see |atp-:ToggleNn|,
	when g:atp_mapNn=1 the |atp-:S| command is used). If 'wrapscan' is
	set and g:atp_mapNn=1 the search will wrap around the beginning of
	the project (not the beginning of the current buffer).

	You can unmap these keys and use <Plug>GotoPreviousSubSection,
	<Plug>GotoPreviousSection, <Plug>GotoPreviousChapter,
	<Plug>GotoPreviousPart to define new maps.


	Note: If you leave the default value of |g:atp_forward_motion_leader|
	then ATP remaps |<<| to << and also |v_<| to <<. |<| is working and is
	not touched by ATP. If you have |'timeout'| set then the map is
	executed faster, if you use |'notimeout'| this workaround it makes
	these operators work.

	Note: If you set |g:atp_forward_motion_leader|="{" then ATP remaps |}|
	operator to {{


Previous commands where using relative position - goto next/previous
section/chapter. The following commands/maps will go to section/chapter as
counted from first one.
							*atp-:SSec* *atp--S*
							*atp-:Sec*  *atp--s*
							*atp-:Chap* *atp--c*
							*atp-:Part* *atp--p*
:[count]SSec
nmap -S
:[count]Sec
nmap -s
:[count]Chap
nmap -c
:[count]Part
nmap -p
	Go to subsection/section/chapter/part [count] from begin of the
	section/chapter/document, i.e. 3]s will jump to section 3 in current
	chapter. Mark ' is preserved.

	Note: if you are in a section which has no subsections :SSec and -S
	will go to next section, the same applies to other section types.

	You can set the leader for maps with *g:atp_goto_section_leader* .


    							*atp-:SkipCommentForward*
							*atp-]star* *atp-]%* *atp-gc*
:[count]SkipCommentForward 
nmap [count]]* [count]]% [count]gc
	Go to end of current/next comment group. Do this [count] times. The
	default [count] is 1.

	Note: if |g:atp_VimCompatible|=1 (the default) it goes one line below
	the last commented line, if it is 0 it goes to the end of the comment.

	Note: This commands wraps around the begining/end of the file. The
	'wrapscan' option applies.
    							*atp-:SkipCommentBackward*
							*atp-[star* *atp-[%* *atp-gC*
:SkipCommentBackward 
nmap [* p% gC
	Go to beginning of current/previous comment group

	Note: if |g:atp_VimCompatible|=1 (the default) it goes one line above
	the last commented line, if it is 0 it goes to the begin of the comment.
							*atp-:ToggleStar*
:ToggleStar 	 	 
map |<LocalLeader>|s	  
	Add/removes a star from the current environment (if it is not one
	belonging to the list: >
		    g:atp_no_star_environments
<	See |b:atp_StarEnvDefault| and |b:atp_StarMathEnvDefault|.

							*atp-:InsertEnv*
:InsertEnv[!] {envname}
	This command inserts environment {envname} and puts the cursor at the
	end of \begin{{envname}} statement. To open new line below use |o|.
	If used with bang the environment is inserted in line.

							*atp-:ToggleEnv*
:ToggleEnv	 	
map <S-F4>    		
	mapped to <F4> and <S-F4>, switches environment        	name. See
	(i.e. echo ) g:atp_toggle_environments_1...7 (you can change or add
	your own variables, just add numbers - they must be consecutive).          	
	
	Read |g:atp_toggle_labels| below how it handles the prefixes of
	labels.

							*atp-:ChangeEnv*
:ChangeEnv		
nmap <F4>
	This does the same as the above command but asks for environment name

	Read |g:atp_toggle_labels| below how it handles the prefixes of
	labels.

							*g:atp_toggle_labels*
	The commands |atp-:ToggleEnv| and |atp-:ChangeEnv| changes the
	prefixes of labels (if there is one, which belongs to
	g:atp_shortnames_dict) and all ref's (\ref, \eqref and \pageref).  You
	have to turn on this feature by putting g:atp_toggle_labels=1 (by
	default it is 0). If there is a label (\label{...}) to which it wants
	to change it doesn't change labels and issue a Warning Message but as
	this changes your file it is turned off by default. It will still
	change the labels if there is a reference \(\ref{...}, \eqref{...},
	etc) (with undefined label).

	In project files this is done in all files belonging to the project.
	Changes are not saved by default (ATP uses |'hidden'| option, so when
	you use q! or qa! all changes will be lost).

							*atp-:ChangeLabel*
:ChangeLabel
	This command changes label in the current line and all its occurrences
	inside \ref{}, \pageref{}, \eqref{} commands. 

	In project files this is done in all files belonging to the project.
	Changes are not saved by default (ATP uses |'hidden'| option, so when
	you use q! or qa! all changes will be lost).
							*atp-:WrapEnvironment*
:WrapEnvironment {environment} 
vmap <F4>		
	Mark part of the text and wrap it into environment given as the
	argument, the map will let you choose the environment name.

							*atp-:Wdiff*
:Wdiff {old-file} {new-file}
	This is diff using the GNU wdiff. This command will split the view and
	show the wdiff output. You can use ]s and [s to go to next previous
	change. The deleted parts of {old-file} are marked embraced into
	{=...=} and highlighted with |hl-DiffDelete|. The added parts of
	{new-file} are embraced with {+...+} and highlighted with
	|hl-DiffAdd|. If the preambles differ you will be asked which one to
	use in the diff file.

	This is an alternative for latexdiff program, but is much faster.

	The diff file might not compile well (thus the b:atp_autex is set to
	0 by default), this is mainly because the math environments can be
	break and the output might contain: \( a {= =c\)=} {+ !=c\)+} Other
	things which are not taken into account are changes of environment
	names, changes of coordinates in tikz. It would be nice to tell to
	wdiff to not diff them, but this is not implemented.

	After you resolve such conflicts the file should compile nicely
	(though I didn't do many tests). After that you can change {=...=} and
	{+...+} for something better. For example you can change {= and =} for
	\textcolor{red}{=} and {+, +} for \textcolor{blue}{+}. If you resolved
	syntactic conflicts in a very nice way you can change whole {=<old>=}
	for \textcolor{red}{<old>} and {+<new>+} for \textcolor{blue}{<new>}.
	For this you can use the following Vim command:

							*atp-:NiceDiff*
:NiceDiff
	(which also remaps ]s and [s and keeps the highlighted areas).
	The :NiceDiff command, although I tried, is not changing all the regions,
	I will try to fix this in next releases. (Thus not all parts of the output
	file might be highlighted).

							*atp-:Dsearch*
:Dsearch[!] [/]{pattern}[/] 					
	The {pattern} argument is optional. It is any vim pattern. Finds all
	definitions which matches the pattern. It looks in the main file (only
	in the preamble, unless the optional bang '!' is used) and all the
	input files (except bib files). This command respects the options:
	'ignorecase' and 'smartcase'. You can override them with '\C' (match
	case what follows) and '\c' (ignore case in what follows).

	It works likes [D but handles multi line definitions.

*g:atp_DsearchMaxWindowHeight* = 15
	You can set the maximal height of the window which shows the results of
	|atp-:Dsearch| (default is 15).

							*atp-:FontSearch*
:FontSearch[!] [pattern]				
	For example:
	:FontSearch ^t1
		will list all the fd files in your tex distribution which
		names starts with t1 (i.e. which describes fonts in encoding
		'T1')
	:FontSearch! bookman
		will list all fd files which full path matches 'bookman'.

	In the opened window there are several mappings defined:
	    <Enter>   	open the fd file under the cursor
	    <Tab>	list fonts defined in the fd file (shows the command
			that you can use in your tex file to use this font)
	    p		preview the fonts defined in the fd file under the
			cursor, do not shows the latex source. 	
	    P		preview fonts and show the latex source 
			(then you can see the errors why the preview was not
			produced; in many cases there are no encoding files or
			fonts themselves for which you have to look in CTAN
			archive yourself; or YOU CAN just SEE HOW TO USE 
			FONTS :) )
	    q 		close the window (actually, delete the buffer using
		       :bd, it will be still in the list if you type ":ls!",
		       so even then you can reload previous searches.)  

	In addition to 'p' and 'P' maps there is a :Preview command. 
	Note: the maps 'p' and 'P' work in both normal and visual mode.
	You can select a part of the text and use this maps or the command
	:Preview to make one preview file for all the font files.


	The same mappings are defined in the window with fd file opened
	(except <Enter>, <Tab>).  

	Additionally, read |font-lowlevelcommands| to learn how to use
	|\usefont|, |\fontsize|, |\selectfont| and other such commands.
	The 'Latex 2e font selection' by 'LeTeX3 Project Team' might be very
	useful. It is available on the net (you probably have it in your tex
	distribution if it is installed with the documentation, if not check
	the CTAN archive).

	ATP also has a very nice completion for various font declaration
	commands, see |atp-completion-fontdeclaration|.

	Hopefully, this will help your documents to become beautiful :)

							*atp-:FontPreview*
:FontPreview[!] {fdFile} [encoding] [keep_tex]
	Previews all fonts defined in fd file matching the pattern <fd_file>
	with encoding [encoding] (optional). If [keep_tex] is 1 (default is 0)
	it will keep the latex source file for debugging purposes.

	Without [!] it matches just the name of the fd files, with [!] the
	pattern {fdFile} matches for full path.

	It returns a list of fonts which fd files matches the {fdFile} pattern in
	[encoding]. You will be asked to chose for which files make a preview,
	possible answers are: >
			1,2,3
< 	which is equivalent to >
			1-3
<	you can also mix this notation: >
			1,2-5,7	
<	As in FontSearch command the [keep_tex] variable specifies if
	the source file will be shown (for debugging purposes, or just to look how
	to use the font :).


							*atp-status-line*
:Status[!]						*atp-:Status*
(:ATPStatus[!])						*atp-:ATPStatus*
	This command sets the status line, which include: the name of currently
	edited chapter (or section) the value of |b:atp_OutDir| (unless used
	with bang "!") and it will warn you if |b:atp_OutDir| variable is not
	set. Note: this command will set the variable |g:atp_statusOutDir|.
	The status line will also contain the information about processing
	compilation: see |atp-status-line-notification|, |g:atp_ProgressBar|.
	This function is called at startup unless the variable
	'|g:atp_statusline|=0' is set. The status is set by the autocommand: >
	    au BufWinEnter,BufWinEnter,TabEnter *.tex :call ATPStatus()
<	In this way every opened window with a '*.tex' file will get the correct
	status line.

	If there was a command with name 'Status', atp is not overwriting it,
	it uses ATPStatus name.

							*g:atp_statusOutDir*
	Note: if you set g:atp_statusOutDir=0 (the default is 1) then the
	output directory will be not seen in the statusline. This variable
	only controls the status line at startup. If you want to remove/add
	output directory rather use |atp-:Status| command.

ToDo({keyword}, {stop}, [bufname])			*atp-function-ToDo*
:ToDo[!] [bufname]					*atp-:ToDo*
:Note[!] [bufname]					*atp-:Note*
	The function list all the lines of the buffer [bufname] which match
	for the pattern '^\s*%.*{keyword}'. The {stop} argument is the pattern to
	before which to stop. The optional argument is the buffer name
	(the buffer name completion is set on). If not given the current
	buffer is assumed.  You can set highlighting for this command by:
		highlight atp-Todo ctermfg=... 	guifg=...
	The command :ToDo sets keyword='^\s*%\s*$\|^\s*%\c.*\<note\>' and
	stop='^\s*%.*\c\<note\>', and the command :Note sets
	keyword='\c\<note\>' and stop='^\s*%\s*$\|^\s*%\c.*\<to\s*do\>'. This
	prevent from listing ToDo lines with Notes and vice versa and stops at
	lines which contains only '%'. With bang "!" the '^\s*' is not
	prepended to the patterns.

  							*atp-:WordCount*
:[range]WordCount[!]
	The command to compute the number of words. With bang [!] it will show
	the word count of each input file. It uses 'detex' program (which is
	present in 'texlive') to remove the latex markups prior to word
	counting (done by the external 'wc' program).  Note: This command will
	first save the file. 

	If [range] is not given (or is the current line) it counts words in
	whole file, otherwise counts words in the given range.

							*atp-:Babel*
							*g:atp_babel*
:Babel
	If |g:atp_babel| variable is set on start up to 1 (however, the default
	value is 0, you can use |vimrc| or |atprc| file to switch it on) then
	ATP will set the |'keymap'| option according to the default babel
	language (which is the last language passed to babel as optional
	argument [lang_list] in \usepackage[lang_list]{babel}). 
  
	If |g:atp_babel| is set to 1 the keymap name is shown in the status
	line (if you use the |atp-status-line|.
							*g:atp_keymaps*
	The |g:atp_kemaps| variable is used to translate babel language name
	to 'keymap' value. The default is something like: >
    let g:atp_keymaps = { 
		\ 'british'	: 'ignore',		'english' 	: 'ignore',
		\ 'USenglish'	: 'ignore', 		'UKenglish'	: 'ignore',
		\ 'american'	: 'ignore',
	    	\ 'bulgarian' 	: 'bulgarian-bds', 	'croatian' 	: 'croatian',
		\ 'czech'	: 'czech',		'greek'		: 'greek',
		\ 'plutonikogreek': 'greek',		'hebrew'	: 'hebrew',
		\ 'russian' 	: 'russian-jcuken',	'serbian' 	: 'serbian',
		\ 'slovak' 	: 'slovak', 		'ukrainian' 	: 'ukrainian-jcuken',
		\ 'polish' 	: 'polish-slash' }
<	When the value is <ignore> then the function <SID>Babel() (or the
	command |atp-:Babel|) will ignore setting keymap option for this
	language. Using the above syntax you can set this variable in |vimrc|
	or |atprc| file.

	This is useful if you in day to day work use one language, but some
	times you write a tex file in some other language.

							*atp-:ShowOptions* 
:ShowOptions[!] [pattern]
	This will show values of variables that are currently set. 
	With bang it also shows global variables defined in
	'ftplugin/ATP_files/options.vim' (that means almost all global
	variables). Completion lists are filtered out by default. 

	The optional argument [pattern] is used to filter variables names with
	the given pattern.

	TIP: if you are looking for a variable you can use this command to
	find it.

							*atp-:HelpEnvIMaps*
							*atp-:HelpMathIMaps*
							*atp-:HelpVMaps*	
:HelpEnvIMaps
:HelpMathIMaps
:HelpVMaps
	These commands list valid mappings defined by ATP (unless g:no_plugin_maps or
	g:no_atp_maps are defined).

:Map[!]	 {pattern}					*atp-:Map*
:Nmap[!] {pattern}					*atp-:Nmap*
:Imap[!] {pattern}					*atp-:Imap*
:Smap[!] {pattern} 					*atp-:Smap*
:Vmap[!] {pattern}					*atp-:Vmap*
:Omap[!] {pattern}					*atp-:Omap*
:Lmap[!] {pattern}					*atp-:Lmap*
	The {pattern} is matched against the right hand side of a map as shown
	by the corresponding |:map| command. If |<bang>| is added the pattern
	is matched against output of [nisvol]map commands with only first
	column removed (which indicates the map mode).

	The Imap can also find imaps which are not defined in normal mode
	(there are such maps in ATP), and thus are invisible while looking at
	the output of |:imap| command).
.

							*atp-:ShowPackages*
:ShowPackages	lists LaTeX packages defined in the preamble.
							*atp-:Preamble*
:Preamble	echoes the preamble to vim pager.							

  							*atp-:ReloadATP*
:ReloadATP 
    Reloads ATP plugin: variables, functions, and maps. Note that maps are not
    deleted.

================================================================================
							*atp-latex-box-settings-compilation*

Compilation ~

*atp-g:vim_program*			Default: autodetected

	Vim program to use on command line for callbacks.
	If autodetect fails, defaults to >
	'/Applications/MacVim.app/Contents/MacOS/Vim -g'
<	on MacVim, or to |v:progname| on other systems.

*atp-g:LatexBox_latexmk_options*	Default: ""

	Additional options to pass to latexmk during compilation, e.g, "-d".

*atp-g:LatexBox_output_type*	Default: "pdf"

	Extension of the output file. One of "pdf", "dvi" or "ps".

*atp-g:LatexBox_autojump*		Default: 0

	Automatically jump to first error after calling latexmk.

================================================================================
TABLE OF CONTENTS WINDOW				*atp-toc-window*

	For the table of contents command and maps read |atp-:TOC|.

	The Table of Contents window is used by both |atp-:TOC| and |atp-:Labels|
	commands.

	In the Table of Contents window there are the following nmaps:

	    'e' 	to echo the line from your tex file
	    'y' or 'c' 	to yank the label of the chapter under the cursor
			    to a register, if it exists,
	    'p' 	to paste it directly to your tex file (just after the
			    current cursor position), 
	    '[N]s'	it splits the window with your tex source file and
			    sets the current line to the beginning of the
			    chapter/section or label under the cursor.
			    If [N] fiven the new window will be that heigh
			    (like with |:split| command). In ToC window |zt| is
			    also used.
	    'q' 	to quit, 
	    <Enter> 	to go to the section under the cursor and close ToC.
   <space>, <LeftMouse> to go to the section under the cursor but
			leave ToC open.
	    '_' 	to go to the section under the cursor and return to 
			ToC afterwards.
	    'zc'	to fold section/chapter/... . You can mark several
			lines in visual mode and use 'zc' to fold them at
			once. 
			Limitation: ~
			It cannot fold subsections in a right way when the
			section is folded. In particular, this applies when
			folding several sections with subsections in visual
			mode.

	There are also commands: ':C' and ':P', which do the same as 'c' and
	'p' mappings. They all call the function 'Yank(<where>)', the argument
	<where> can be one of: '@<register name>' or 'p'. 

	You can also delete and paste sections using the Table of Contents
	window:
							*atp-:YankSection*
							*atp-:DeleteSection*
							*atp-:PasteSection*
							*atp-:SectionStack*

	These commands are available in table of contents. They act on
	parts/chapters/sections/subsections/subsubsections.
>
    :YankSection [register]
<	Yank the section under the cursor (in table of contents) to the given
	register. If the register is not specified use the unnamed register
	(|registers|).
	 
	 The other commands do not use registers but an internal stack.
>
    :DeleteSection
    :PasteSection[!]
    :SectionStack
<	Using ':DeleteSection' you can delete the section under cursor together 
	with all its subsections.  /Section can be one of: part, chapter,
	section, subsection, subsubsection, or bibliography/.  Deleted section
	will be added to a stack which can be shown using the command
	':SectionStack' There is a command to paste the section from section
	stack ':PasteSection'. By default it pastes the most recent element in
	the stack. Passing a number will paste that element of the stack
	/bear in mind that then numbers of sections in the stack will change/.

	':PasteSection' puts the section just after where current section
	ends (section under the cursor in the ToC buffer). With bang "!" it
	puts before.

	Note: If you use bibtex commands to make bibliography ATP finds the
	line which contains '\bibliography' command. And then searches
	backward for the first line which is a blank line. The next line is
	assumed to be the first line of bibliography.  Thus to move the last
	section before bibliography or the bibliography itself its better you
	put a blank line before bibliography commands.  The same applies for
	bibliographies put in the middle of document (end of a chapter, part,
	etc.) The end of bibliography is found in the same way as the end of
	subsubsection.  If you use
	\begin{thebibliography}:\end{thebibliography} there is no such
	a problem.

	If you want to paste a section before the first section, use the line
	with the file name. 
							*atp-:Undo*
>
     :Undo 
     nnoremap u, nnoremap U, nnoremap g-, nnoremap g+ 
<	You can use undo. The :Undo command will undo in the buffer under
	the cursor (it switches to the correct window, using the Vim undo
	function, and runs :TOC command - so after all your back in ToC.). The
	':Undo' command has one argument - the Vim undo command to use, it is
	one of: 'u/U/g-/g+' (the default is 'u'). They are mapped to 'u','U',
	'g-' and 'g+'.  (only in the ToC buffer).  Note: ':Undo' command
	doesn't changes the Section Stack.

	There is one more level of security: There is a global variable which
	stores all the deleted sections together with some information about
	them: >
			g:atp_SectionBackup
<	it is a Vim list (see |List|). Each entry is a list of the following format: >
		[ <title>, <type>, <deleted_section>, <section_nr>, <file> ]
<	where <title> is the section title, <type> is one of: part, chapter, 
	section, subsection, subsubsection bibliography or abstract.  Deleted
	section is a list of deleted lines, <section_nr> is the number of the
	section that it had before delete, <file> is the full path to the
	file which it comes from.  If you need to use it, you can use the Vim
	function |append()| to put the <deleted_section> in the right place.

	NOTE:
		You may want to have a map: >
				:au FileType toc_atp nnoremap dd :DeleteSection<CR>
<		this can be put in your '$HOME/.atp.vim' configuration file.
			        			*atp-:Fold*
>
    :Fold, :'<,'>Fold
<	Fold section[s], works in the same way as 'zc' (as above) with the same
	limitations.


================================================================================
FOLDING							*atp-folding*
 I found a nice folding file (written by Johannes Zellner, added with his
 permission) there are two options:
 g:atp_folding = 0					*g:atp_folding*
	 enables/disables folding. you should set in your |vimrc| or |atprc|
	 files. if you reset the value on the fly you need to issue
	 '|:filetype| detect' command in order for changes to take place.

 g:atp_fold_environments = 0				*g:atp_fold_environments*
	 enables/disables folding of environments. By default folding is
	 disabled since it slows down vim.
================================================================================
SEARCHING IN BIB FILES					*atp-bibsearch*

		___________________________
		Table of Contents: ~
		|atp-BibSearch|
		|atp-bibpatterns|
		|atp-bibflags|
			|atp-bibflags:default|
			|atp-bibsearch-show-only-keys|
			|atp-bibflags:+|
			|atp-bibflags:output|
			|atp-bibflags:all|
			|atp-bibflags:last|
			|atp-bibflags:add-flag|	
			|atp-bibflags:examples|
		|atp-:BibChoose|	
		|atp-bibsearch-highlight|
		|atp-:BibSearch|

		____________________________
		Naming Conventions: ~

		@article{<label>,					\	
			author = { .... },		<-- bib entry   | 
			title  = { .... },				 > bib field
			journal= " .... ",				|
		}							/	

			article 		<-- bib field keyword 
			author,title,...	<-- bib entry label 	
			<label>			<-- bib field label 	


One more function is provided which searches the bib files for bib fields, 
and for the bib field labels for the latex command \cite{}.

:BibSearch /{pattern}/ [flag] 				*atp-:BibSearch*
	which do what you expect. The arguments should not be quoted and
	separated by a white spaces (if you want to include a white space use
	'\ '), for more see |f-args|. If you do not provide any argument then
	all entries of all bib files will be shown. 
							*g:atp_bibsearch*
	Note: {pattern} should be a PYTHON regular expression not vim regular
	expression (they are similar to very magic vim expressions, see |\v|).
	Unless you set |g:atp_bibsearch|="vim" (the default is "python").
	Python regular expressions are quite similar to vim with 'nomagic' set
	( grouping with '(' and ')', with separating alternatives with '|').
	But there is no vim '\&' in python regexp.

	The pattern to highlight matching string is passed to |@/| hence you can
	use |n| and |N| in the BibSearch buffer. This will only work for
	{pattern} which is both vim and python regular expression.

	See |atp-bibflags| for the [flag] argument.

							*atp-bibpatterns*
	Note: Upper pattern is vim pattern lower one is python regexp. 

	Before the match all the ligature symbols and {:} are removed. For
	example \`a, \' e, \oa,\ea are substituted with a, e, oa, ea
	(respectively).  Note that the space in \' e is also removed. Each
	line (without ligatures) of every bib file found in your tex document
	will be matched against the pattern, for example if the pattern is:
>
 		'author.*Grothendieck'
 		'author.*Grothendieck'
<
	the BibSearch function will find all the bibliographic fields
	which in one line have the words 'author' and 'Grothendieck' (in most
	cases it means that you will see only works of Grothendieck). Another
	example:
>
		'^\(\s*author.*Joayl\)\|Galois Theory'
		'^(\s*author.*Joayl)|Galois Theory'
<
	will result in all bib fields which author is Joyal or 
	which includes the words 'Galois Theory' (which by the way appear in
	many article/book titles), yet another example:	
>
		'author.*Joayl\|title.*Galois Theory'
		'author.*Joayl|title.*Galois Theory'
<
	This will match against all bib entries written by Joyal or which title
	includes the word 'Galois Theory'.
>
 		'author.*Joyal\&.*Tirney'
		 ! python has no '\&' !
<	
	will find all the bib entries which were written by Joyal and Tirney
	(and maybe somebody else). 

	For now, there is no possibility to filter bibliographic entries which
	both match a pattern in separate lines, i.g. to show all bib entries
	written by Joyal on 'Descent Theory'.

	Before a match, all '{', and '}' are deleted from the line of the bib file.
	But you will see them in the output (what can be useful for debugging
	errors in bib files)

	Note that in Vim patterns should be quoted using '...' not "...".   

	Further examples are supplied after the next section
	|atp-bibflags:examples|, which describes other functionalities of the
	BibSearch/BibChoose commands.

							*atp-bibpattern:last*
							*atp-bib-b:atp_LastBibPattern*
	The variable 'b:atp_LastBibPattern' stores the last pattern used by
	bib search.

							*atp-bibflags*
	The optional argument [flags] chooses what and in which order you want
	to see the  bib entries found (entries are listed in the order they
	appear in bib file).  Flag is a word made of letters.  There are three
	kinds of flags: entry flags which matches against labels of bib
	entries, like author, title, etc..., and keyword flags: which matches
	against keywords of bib fields: @article, @book, @techreport, etc...
	and two special flags 'All' and 'L'. A flag is a word on letters:
>
		a  - author
 		e  - editor
 		t  - title
 		b  - booktitle
 		j  - journal
 		s  - series
 		y  - year
 		n  - number
 		v  - volume
 		p  - pages
 		P  - Publisher
 		N  - Note
 		S  - School
 		h  - howpublished
 		o  - organization
		u  - url	
		H  - Homepage	
  any other letter - do not show anything but the first line of bib entry 
		@a - article 						/@article/
		@b - book or booklet 					/@book,@booklet/
		@B - Booklet 						/@booklet/	
		@c - incollection 					/@incollection,@inbook/
		@p - proceedings, inproceedings, conference   		/@proceedings,@inproceedings,@conference/
		@m - misc 						/@misc/
		@M - Manual 						/@manual/
		@t - master or PhD thesis  				/@masterthesis,@phdthesis/
		@T - Techreport 					/@techreport/
		@u - unpublished  					/@unpublished/		
		All - all flags						(see |atp-bibflags:all|)		
		L   - last flags					(see |atp-bibflags:last|)		
<
	Examples:
>
		tayu@a		--> show the entries: tile, author, year, url of matching articles.
		baeP@b		--> show the entries: booktitle, author, editor, 
 							publisher of matching books (@book,@booklet).
<
	Flags '@.' are filtered out, if one does not belong to the one above
	then it is deleted. You can see which flags are defined using
	ShowOptions function/command (they are listed as Available
	KeyWordFlags).
							*atp-bibflags:default*
	The default flag is stored in the global variable g:defaultbibflags and is
	equal to 'tabejsyu'. This means that the output for each bib field found 
	will include the 
		title
		author
		booktitle
		editor
		journal 
		series
		year
	if title,author,... are specified in the bibliography for the given
	position. If there are many position which match you can set flags to
	be as simple as possible to include more lines on the screen. For
	example 'tabe' is quite reasonable (note that all bib entries are
	matched separately, i.e. if a bib field has both 'title' and 'booktitle'
	bib entries it will give you both of them.

							*atp-bibsearch-show-only-keys*
	If you just want to list just the lines with bib fields keywords:
	@article{, @book{, etc. supply a flag which do not belongs to
	'g:defaultallbibflags', for example 'X', or 'X@a'
	
							*atp-bibflags:+*
	You can also specify flags with '+', for example: 
>
	flags='+p'
	flags='+@b'
<
	This feature ADDS FLAGS TO THE DEFAULT VALUE defined in the variable
	g:defaultbibflags (see |atp-defaulbibflags|). The first will result in
	showing the default entries and the page number, the second will
	result in showing only books with the default bib entries. You can
	specify as many additional flags as you wish.  *atp-bibflags:output*
	Note that the function shows the line with database file name if there
	are entries in this bibliography which match the pattern thus,for
	example, if you specify the flag '@a' and you see the line with
	database file name, but you do not see any bib entry, then in this
	database there are bib fields which match but these are not articles.
	
							*atp-bibflags:all*
	The flags='All' is a synonym of flag=g:defaultallbibflags which by default is
	equal to'tabejfsvnyPNSohiuHcp' i.e. all flags in this order. If you
	add your own flag you should change this global variable. You can add to
	this flag any flag which contains '@' (see |atp-bibflags|) by
	the plus operator, i.e. All+@a@b or +@aAll will give the same result.

							*atp-bibflags:last*
							*atp-bib-b:atp_LastBibFlags*	
	The variable 'b:atp_LastBibFlags' stores the recently used flags. The flag
	'L' sets the flags for this search to the value of 'b:atp_LastBibFlags'.
	You can write '+L@a', '+L@a', 'L@a' or '@aL' but not '+@La', if you
	want to add some flags to previous searches. Next time the flag 'L'
	will change the meaning (i.e. it is really the last time not earlier
	:) However, there is no '-' :( '-@aL' could be helpful.
	 
	The variable 'b:atp_LastBibFlags' is not changed when you use the 'All'
	flag.

							*atp-bibflags:add-flag*
	You can add your own flags but not keyword flags (i.e. @a,@b,...).
	Just add an entry to the dictionary g:bibflagsdict. (:ShowOptions v to
	see its current value), For example
>
	let g:bibflagsdict=extend(g:bibflagsdict, 
	\ { '<flags_name>' : [ '<bib_entry_name>': '<how_to_show>'] })
< 
	where, <flags_name> is the flag to use (it should be one letter), it
	must be different from the defined flags, <bib_entry_name> is a
	lower case bib entry name, like 'title', 'url', etc., <how_to_show> if
	you want to have a nice output put the bib entry name and that much of
	white spaces to get 13 strings.

	Some examples:					*atp-bibflags:examples*
>
	    :BibSearch 
<				Above command shows all bib fields with
				the default flags (might be slow, why not to
				open bib file with :GotoFile)
>
	    :BibSearch @ yt	
<				and this is a tip how to show all bib fields with
				different flags than the default ones(the '@'
				will match at every bib field!). It is
				equivalent to:
>
	    :BibSearch // yt

	    :BibSearch /title[\s.]*Galois Theory/  aetb
<
	The next one shows all bib fields which were written by Joyal and
	Tirney (and may by somebody else).
>
	    :BibSearch author.*Joyal\&.*Tirney
< 	This is not possible with |g:atp_bibsearch|="python" (the default).

		
:{BibEntry}Yank [RegisterName]				*atp-:Yank*
map {count[register]}c, map {count[register]}y
	This function/command is only available in the window with BibSearch
	results and allows to copy a bib entry key to a register or directly
	to the last opened buffer (after the cursor position). It is mapped to
	'c' and 'y'. You will be asked to give the number of bib entry to
	yank:
>
	    <bib entry number><register name><Enter>	- to copy it to a register
	    <bib entry number><Enter>			- to copy to the " register
	    <Enter>					- to skip the choice
<	When the {count} is given the bib item {count} will be copied to the
	register ".

	For example: >
		:5Yank e
		:7Yank +
		:2Yank
<	Copy the bibkey to register e,+, or " (this might depend on the
	'clipboard' option in which register the bib key will be put). The
	same you will obtain using the nmaps y or c. 
	
	This commands and maps are only in the BibSearch buffer.

							*atp-:Paste*
:{BibEntry}Paste [RegisterName]
map {count}p, {count}P
	The syntax is the same as for |atp-:BibYank|. It paste the bib entry
	to the tex buffer (where the |atp-:BibSearch| was inoked). The bib
	entry is also copied to the " register.

							*atp-bibsearch-highlight*
	The colours of the output are set by the syntax file
	'syntax/bibsearch_atp.Vim'. All groups except one are the same as in
	the syntax file for bib files ('syntax/bib.Vim' in your $VIMRUNTIME
	directory). Their names are 'bibsearchEntryKw' instead 'bibEntryKw'.
	The one that is differently defined 'bibsearchComment'.  Which is
	changed in that way to highlight the bib file names.  One additional
	highlight group is: 'bibsearchInfo'. It highlights the number of
	entry and its line number in the bib file. By default all bibsearch
	groups are linked to the corresponding bib group, the bibsearchInfo
	group is not set.
	
	In a colour file (~/.Vim/color/*.Vim) you can use these groups to set
	colours.  See |highlight| or just read a colour file. For example,
	this is a nice set of colours for dark background 
		
							 	
								
-----------------------------------------------------------------------------
BIBSEARCH COMMENTS					*atp-bibsearch-comments*	
					
	Please do not hesitate to report any bug to the mailing list
	|atp-mailing-list|.
	
	The algorithm will work only if all kind of bib entries of your bib
	file are included in the list g:bibentries. However, changing just
	this variable is not enough. In that case the search engine (function
	s:search) will produce correct output, but the function which displays
	found entries, will not know how to work with the new entries. One
	would have to add an entry to the dictionary 'g:bibflagsdict'. If
	it is the case, please let me know: |atp-mailing-list|.  

	As you can see entries of the type '@string' which can be used in bib
	files are not supported (i.e. there is no function which substitutes
	the variables defined in @string to their values), but it is doable.
			@string{ Name = Value }
			
================================================================================
COMPLETION			                        *atp-completion*

The completion is by default mapped to <C-X><C-O> (expert mode) and <C-X>o
(non expert mode). However if you set |g:atp_tab_map| to 1 (in your |vimrc|
or |atprc| file), then  <Tab> (expert mode) and <S-Tab> (non expert mode) are
used. For example if you type \math<C-X><C-o> you will get a list of choices
which completes this command. (See ':h popupmenu-completion' and ':h
completion' for more).

							*atp-completion-expert-mode*
							*atp-completion-non-expert-mode*
There are two completion algorithm: expert mode and non expert mode: the
keyword for completion in expert mode must match at the begining, in non
expert mode any where. Also in expert mode the list of possible completions is
smaller (for example there is no '\lneqq', there is only '\lneq').

Note: Non expert mode doesn't check if you are editing math (see
|g:atp_MathOpened|), and is useful when you want to complete a non-math
command inside mathematics.

							*atp-tab-note*
							*g:atp_tab_map*
If you prefer to use map <Tab> key then you can define |g:atp_tab_map|=1 in
your |vimrc| file or atprc file |atprc|. Note that Vim can add/remove
tabshift width from the beginning of line in other ways: in normal mode with
|>>| and |<<|, in insert mode: |i_CTRL-T|, |i_CTRL-D| and in visual mode with
|>| and |<|. Also you can use |atp-g>| and |atp-g<|. The alignment of tabular
and other environments can be done with |atp-:TexAlign| command. 


You can switch off/on completion modes adjusting the variable
|g:atp_completion_active_modes|, all names of completion modes are stored in
the variable |g:atp_completion_modes|.

							*g:atp_local_completion*
If |g:atp_local_completion| is set to non zero value, then input files will be
scanned for \def, \newcommand, \newnevironment and \newtheorem commands and
they will be used for completion (with |atp-:LocalCommands|). If its value is
1 then this will be done during first completion, if it is set to 2 then this
will be done at start up. The default value is 2 when vim has |+python|
feature otherwise it is 1. With |+python| this is done at every time you
use the completion.

NOTE: if you press <C-X><C-O> but then you changed your mind, the completion
pop-up menu allows to cancel completion: press <C-p> (i.e.  go up - some
times more than once) and then press <Space>.

Note: The completion checks the preamble for definitions of LaTeX packages. If
a supported package is present (for example: tikz) then the completion will
contain additional commands. If you add a package or a class you should unlet
corresponding variable: |g:atp_LatexPackages| and |g:atp_LatexClasses| and ATP
will regenerate them when necessary.

							*atp-:ToggleTab*
:ToggleTab			{only available if g:atp_tab_map=0}
nmap, imap `<Tab> 
    It is a command to toggle the tab map off/on: :ToggleTab, it is also mapped
    to `<Tab>. 
    Note: see |atp-Tab-note|.

DICTIONARIES ~
    I added extended versions of dictionaries of latex-suite to ATP (the files
    dictionaries/dictionary and dictionary/SIunits). They are added to
    |'complete'| vim option, so you can use them through |ins-completion|.
    I made one more dictionary (dictionaries/ams_dictionary) with ams commands
    and environment names. It will be added to the vim |'complete'| option if
    you use amsmath package or if the document class is one of the standard
    ams classes or of |g:atp_amsmath| is set to 1.

COMPLETION MODES		                       	*atp-completion-modes*
							*atp-completion-commands*
	commands ~
		if g:atp_check_if_math_mode = 1 then the pull of commands
		contains math commands only if there you are inside a math
		environment. This works perfectly if you switch from $:$ and
		$$:$$ to their equivalent (and more up-to-date) \(:\) and \[:\].
		The list of math environment in which ATP will think you are
		editing a math mode is stored in the variable:
		'g:atp_math_modes'. Its entries are two element list of
		patterns which matches the beginning and end of a math mode.
		The '0' entry have to provide the beginning and end pattern of
		in line math '\(:\)', the second for displayed math '\[:\]'.
		Its default value is given below.
	
		If you add a package (like tikz or amsmath, or amssymb) then
		the set of completions will contain extra commands/environment
		names defined in these packages  Because some classes calls
		amsmath package silently setting the variable
		'g:atp_amsmath=1' will ensure that you will get completions
		for these commands. The algorithm checks if you have this
		package declared or if you use some of the standard ams
		class (actually checks if the document class name matches
		'^ams'). 

		If you do not want math commands completions at all define
		':let g:atp_no_math_command_completion=1' (you can put it in
		your |vimrc| or |atprc| file, or define while writing,
		both will work, so you can switch off the math completions
		temporarily).

		The label command completes in a special way: for example in
		a line like:
			\begin{theorem}\lab<Tab>
		will complete to 
			\begin{theorem}\label{thm:
		The dictionary of short names is 'g:atp_shortname_dict'. If
		you do not likes this idea (however it can help you to
		correctly write \ref{ - to avoid referring to lemmas as
		propositions, and also it makes completion for \ref{ nicer
		- you can list only labels for theorems), so if you do not
		want it anyway: 'let g:atp_no_short_names=1' will make the
		work. 
							*g:atp_amsmath*
		If |g:atp_amsmath|=1 or you use one of ams classes, or the
		package amsmath is found by ATP ams math commands and
		environment names will be added to the list of completions.

							*atp-variables-local_completion*
							*b:atp_LocalColors*
							*b:atp_LocalCommands*
							*b:atp_LocalEnvironments*
		By default the first time you are completing an environment
		name or a command a list of locally defined environments and
		commands is made (it takes a few seconds). If you do not want
		to completions for them define "let |g:atp_local_completion|=0",
		if |g:atp_local_completion|=2" then the search for local
		definitions and commands will be done on startup (after
		version 8.4 for this you have to switch off abbreviations by
		setting g:atp_noabbreviations to 1 - but anyway it is not time
		consuming because these variables are loaded from
		|atp-ProjectScript|).
							*atp-:LocalCommands*	
:LocalCommands[!]							
		If you added a command or an environment the command
		:LocalCommands! will update the list of local definitions.
		With bang "!" it update the list of input files
		|b:ListOfFiles| in which the search is done. The output is
		stored in three variables: >
				b:atp_LocalColors
				b:atp_LocalCommands
				b:atp_LocalEnvironments
<		If a command was declared with a arguments (i.e. using \def#1, or
		\def#1#2, etc. or with \newcommand{...}[1]{...}) a single '{'
		is attached. It doesn't match for definitions inside comments.

		This command will also make abbreviations to environments
		found, see |atp-abbreviations|.

		Note: the python version searches for commands, environments,
		...  defined in the beginning of line (with possible white
		spaces).

		Note: the python version of LocalCommands will save the
		current buffer, without saving project script and with
		'nowritebackup' and 'nobackup' set. 

							*atp-completion-tikzpicture*
	tikzpicture ~
		There is an extended support for tikz picture environment both
		in-line \tikz{:} and displayed: \begin{tikzpicture}
		\end{tikzpicture}. The completion works for both commands and
		keywords. The pull of them is enlarged if you add tikz
		libraries. Normal commands are added if you are inside {:}.

		NOTE!: Keyword completion is only active in non expert mode
		(|atp-completion-non-expert-mode|).

							*atp-completion-ref*
							*atp-completion-label*
							*atp-completion-cite*
	ref/label/cite ~
		For label completion puts short names, for ref and eqref
		commands the completions are the labels found in all files
		associated to the main file (the plugin searches the input
		and include files for them). The same for cite: which searches
		also in bib files defined in the main file.

		In the popup menu the first column show the label name, second
		column contains the first letter of the counter name used:
		e for equation, t for theorem, s for section, c for chapter,
		I for Item, etc. - these are the most common things you will
		see. The third column contains the value of the counter. It is
		put in brackets () if it comes from equation counter.

		There is also omni completion (see |i_CTRL-X_CTRL-O|) for
		\cite command. Check it out, as it is very nice (especially in
		gvim!) and very fast. 

		For both completion and omni completion for the cite command,
		the text after \cite{  [ or after a comma after \cite{ ] is
		treated as a regular expression. Thus you can write:

		\cite{.*author1\&.*author2<Tab>

		to get the completions for things written by both author 1 and
		2 (regardless of the order they appear in bib files).

		BibTeX omni completion is triggered by '\cite{', '\citep{' or
		'\citet{'.  For example, assume you have in your .bib files an
		entry looking like: >

		@book {	knuth1981,
				author = "Donald E. Knuth",
				title = "Seminumerical Algorithms",
				publisher = "Addison-Wesley",
				year = "1981" }

		Then, try: >

			\cite{Knuth 1981<CTRL-X><CTRL-O>
			\cite{algo<CTRL-X><CTRL-O>
<

		\ref{{pattern}<Tab> matches the label name for the {pattern}.
		When pattern is matched for a number of a label '^' is added in
		front of the pattern (see below). In this case both completion modes:
		expert and non-expert works in the same way.

		You can also use Vim patterns after '\cite{'.

<		Tab Completion for labels (|atp-completion|) allows to specify
		the number of the counter, e.g. >
					\ref{3.1<Tab>
<		will complete into the label of the counter with value '3.1'.
		As for now you can not specify which counter to complete. You
		can also write '\ref{3.1$' then '^3.1$' is used as a pattern!

		For this two work the aux file must be present.  As for now
		the aux file, if it is not present, is not made.

		This is working with the main document classes: article, book,
		review, amsart, amsbook, memoir. If for some class it is not
		working thanks for reporting me (it's enough to email me just
		the document class).

							*atp-completion-brackets*
	brackets ~
		Closing of brackets {:},{:},[:],(:) (also closes math modes \(:\) and
		\[:\]). 
		Relevant variables are: g:atp_bracket_dict a dictionary of
		brackets by default it consists of pairs '(' : ')', '{' : '}',
		'[' : ']'. There is a second dictionary g:atp_sizes_of_brackets
		which contains all the sizes of brackets in latex plus a pair
		'\' : '\', for closing the math modes: \(:\), \[:\] and the
		brackets \{:\}.
	
							*atp-closing-math*
							*atp-completion-math*
	math modes ~
		\(:\), \[:\], $:$ and $$:$$ will be closed when all brackets
		after the opening \(, \[, $ or $$ are closed. If \[ or $$ is
		in line which matches '^\s*\(\\[\|\$\$\)\s*$' it will be
		closed in a following line.
							*atp-closing-environments*
							*atp-completion-env*
	environments ~
		Completes after '\begin{' and '\end{'. For example
		'\begin{cen<Tab>' will give '\begin{center}' 
		But '\begin{theorem}<Tab>' or
		'\begin{theorem}\label{thm:1}<Tab> will close the environment.
		The algorithm tries to close environment in many natural
		situations: for example when it did found less than one command
		completion. It closes the right environment when they are
		nested (however not in right place!) and it preserves the
		indention. When after \begin{center}\label{...} XXX there is
		something (in place of XXX) it will close the environment
		after the cursor position otherwise in next line
		(\hypertarget{...}{...} command is treated like \lebl{...}).

		The environments opened in tex definitions ('\def',
		'\newcommand', '\renewcommand') will not be closed unless the
		current cursor position is in that line (sometimes one might
		want to have a definition which only opens an environment).

		If you type \begin{envname}<Tab> the cursor position will not
		change. You can use |i_CTRL-M| (|i_CTRL-J| is used by
		|atp-j_motion|) after <Tab> to open new line inside {envname}.
		Otherwise the cursor position will be right after the closing
		\end{envname}.

		See |g:atp_amsmath|.

		Examples: ~
			(the <Tab> indicates in which position the
			<Tab> can be pressed to get the described
			behaviour).
>
			    \begin{theorem}
				    \begin{enumerate}
				    \item .....
				    \item .....
					\begin{minipage} 	
					    ......
					\end{minipage}
					    ......
					    ......<Tab>
					    XXXXXX
					    ......
			    \end{theorem}
<			Usually the closing comes in the next line,
			unless we are inside an environment which is opened
			after the non closed environment: 
>
			    \begin{theorem}
				    \begin{enumerate}
				    \item .....
				    \item .....
					\begin{minipage}<Tab> 	
					    ......<Tab>
					\end{minipage}<Tab>
					    XXXXXX
					    ......
					    ......
					    ......
			    \end{theorem}
<			Then the closing will be put just after the last
			opened environment closes, or
>
			    \begin{theorem}
				    \begin{enumerate}
				    \item .....
				    \item .....
					\begin{minipage}
					    ......
					\end{minipage}
					    ......
					    ......
					    ......
					    XXXXXX
			    \end{theorem}<Tab>
			    ....<Tab>
<			If we are outside the theorem environment,
			'\end{enumerate}' will be placed just above
			'\end{theorem}', and 	
>
			    \begin{theorem}[Joyal\&Tirney]\label{thm:jt}
				    \begin{enumerate}
				    \item .....
				    \item .....
					\begin{minipage} 	
					    ......
					    ......
					    XXXXXX
				    \end{enumerate}<Tab>
			    \end{theorem}<Tab>
<			will put \end{minipage} just above
			\begin{enumerate}. Furthermore, if:
>
			    \begin{theorem}
				    \begin{enumerate}\label{enu:1}
				    \item .....
				    \item .....
					\begin{minipage} 	
					    ......
					    \begin{itemize}
						    ......
					    \end{itemize}
					    ......
					    ......
					    XXXXXX
				    \end{enumerate}<Tab>
			    \end{theorem}<Tab>
<			'\end{minipage}' will be put just above
			'\end{enumerate}'.  Furthermore,
>
			\begin{theorem}[...]\label{...} Let \(C\) be a ....
			......
			......<Tab> XXXXX
<	
		That is, if you like to write \begin{}:\end{} in the beginning
		and end of a line this will be preserved. However, there is no
		support for nested environments then!

							*atp-completion-abbreviations*
	abbreviations ~
		There is tab completion for insert mode abbreviation names
		(use <CTRL-y> to choose one from the list and then type
		<space>, just typing <space> should also work).

							*atp-completion-fontdeclaration*
	font declarations ~
		This is completion for the commands 
		    \usefont{<encoding>}{<font_family>}{<font_series>}{<font_shape>},
		    \fontencoding{<encoding>},
		    \fontfamily{<font_family>},
		    \fontseries{<font_series>},
		    \fontshape{<font_shape>},
		    \DeclareFixedFont{<cmd>}{<encoding>}{<font_family>}{<font_series>}{<font_shape>}{<size>}
		
		It first splits the line and take a part between the commands
		\selectfont (if there is not \selectfont command this step is
		omitted).

		Then if the <encoding> is declared the font families for the
		completion will only come from this <encoding>.

		If <font_family> is defined, <font_series> and <font_shape>
		come from the particular font definition file (the declared
		encoding is used if not the value of
		|g:atp_font_encoding| is used).

		If <font_family> and <font_series> are defined then the
		<font_shape> for this font (in the above encoding) is found.

							*g:atp_completion_font_encodings*
		The completed <encoding>'s are taken from the variable:
		|g:atp_completion_font_encodings|.
		
							*atp-completion-bibstyle*
	bibstyle ~
		Completion for the command '\bibliographystyle{'. Finds all
		"bst" files available in your tex distribution. 

							*atp-completion-documentclass*
	documentclass ~
		Completion for the command '\documentclass'. Returns list of
		all classes available in your distribution.

							*atp-completion-documentclass-options*
							*atp-completion-package-options*
							*atp-completion-packages*
	documentclass options ~
	package options ~
		You can write your own scrip which will add support for
		documentclass or a package. Put it under
		'ftplugin/ATP_files/packages/' directory in your vim path.
		Supported variables:
>
	    g:atp_{dc_name}_options
	    g:atp_{p_name}_options
<		Note: ATP (if |+python|) scans package and documentclass files
		for options, so in general this variables are not needed. The
		values in this variables will be added to completion. They
		might be used if there are options which atp cannot find.
>
	    g:atp_{p_name}_commands
	    g:atp_{p_name}_math_commands
<		These are just list of options/commands. math_commands will be
		added to completion only in math mode.
>
	    g:atp_{p_name}_options_values
<		This variable is a vim dictionary: keys are vim patterns which
		should match a package option, values are lists of the option
		values. See 'ftplugin/ATP_files/packages/caption.vim' for an
		example. This was tested with the following option syntax: >
		    option1=value1,option2={value1,value2}
<		In a similar way works the variable: >
	    g:atp_{p_name}_command_values
<		See 'ftplugin/ATP_files/packages/enumitem.vim' for an example
		(or use ':echo g:atp_enumitem_command_values').
		or 'ftplugin/ATP_files/packages/xcolors.vim' 
		The value of a key in this dictionary might be a string, which
		is supposed to be a name of a function to get list of
		completions. Afterwards this list will be filtered to get
		only matching completions. It should return a vim list. An
		example is in 'ftplugin/ATP_files/packages/xcolors.vim'.
>
	g:atp_{p_name}_loading = { "package" : "option", ... }
<		This variable is a dictionary { "package" : "option" } which
		loads xcolor package, when option is empty means that the
		package is always loading.  Both "package" and "option" are
		vim patterns. See xcolor for an example. Loading through
		document class is not yet supported, but might be added on
		request.

------------------------------------------------------------------
ATP COMPLETION VARIABLES				*atp-completion-variables*

These are all variables which can help to customise the completion:
(if the value is given it is the default, if it is not means it is too long to
put it here).
							*g:atp_completion_limits*
>
 	g:atp_completion_limits		= [ 40, 60, 80, 120, 30 ]
<
	    The above variable specifies how long should atp plugin search for
	    closed/unclosed environments:
	    the first value 	- search for \(:\)  [ in line math ]
	    the second	 	- search for \[:\]  [ displayed math ]
	    the third	 	- search for \begin{<env>:\end{<env>	
	    the fourth	 	- for environments defined in
				  the variable g:atp_long_environments
	    the fifth		- for checking brackets defined in
				  |g:atp_bracket_dict|. You can speed up Tab
				  Completion by removing brackets that you
				  don't use from |g:atp_bracket_dict|.

	    You can also put "-1" as the values of |g:atp_completion_limits|,
	    then the search forward/backward will last till first/last line.
	    However, this makes it run slower.
							*g:atp_long_environments*
>
 	g:atp_long_environments 	= []
<	
	    If some of your environments are very long put their names in this
	    list. Do not forget that is environment <env> is long and is put
	    inside environment <center> then <center> is also long!
				 
	    However, this will not close long environments (for that you have
	    to change the third argument of |g:atp_completion_limits| !). This
	    just prevents closing environments which are closed and to long to
	    see that.
							*g:atp_completion_modes*
>
  	g:atp_completion_modes		= [ 
				\ 'commands', 		'inline_math', 
				\ 'displayed_math', 	'package_names', 
				\ 'tikz_libraries', 	'environment_names', 
				\ 'close_environments' ,'labels', 
				\ 'bibitems', 		'input_files',
				\ 'bibfiles',		'bibstyles',
				\ 'documentclass' ] 	
<				
	    This is the list of completion modes.
							*g:atp_completion_active_modes*
>
	g:atp_completion_active_modes	= g:atp_completion_modes
<		This is the list of completion modes which are active, by
		default all modes are active. Remove a value from this list to
		make it inactive (You can use remove() command, see ':h
		remove()'). 
>
	g:atp_sort_completion_list	= 12
<		If the length of completion list for Tab Completion is longer
		than this value, entries will be sorted alphabetically, else
		they are provided in, I hope, useful order. If set to 0 the
		list will not be sorted (if set to 1 it will be always
		sorted). >
    	g:atp_environments
    	g:atp_amsmath_environments
    	g:atp_shortname_dict
<		It is used to define <short_name> in 
		    \label{<short_name><separator>
		when completing the \label command.
							*g:atp_separator*
>
    	g:atp_separator			= ':'
<		It is used as a separator in:
		    \label{<short_name><separator>
		when completing the \label command.
							*g:atp_no_separator*
							*g:atp_env_short_names*
							*g:atp_no_serparator_list*
>
    	g:atp_no_separator 		= 0
    	g:atp_no_separator_list		= ['', 'titlepage']
<		The following variable if set to one then completion for \label
		command will put short name of the environment where it stand.
		It uses the dictionary g:atp_shortname_dict to get the short
		name. >
    	g:atp_env_short_names 		= 1
<
							*g:atp_commands*
							*g:atp_math_commands*
							*g:atp_ams_negations*
							*g:atp_math_commands_non_expert_mode*
							*g:atp_ams_negations_non_expert_mode*
	These variables are lists which stores LaTeX commands used in
	completion. >
    	g:atp_commands
    	g:atp_math_commands
    	g:atp_ams_negations
    	g:atp_math_commands_non_expert_mode
    	g:atp_ams_negations_non_expert_mode
<			The two last are lists of commands will be add only in 
			the non expert mode (|atp-completion-non-expert-mode|).
>
    	g:atp_amsmath_commands
    	g:atp_fancyhdr_commands
    	g:atp_tikz_environments
    	g:atp_tikz_libraries
    	g:atp_tikz_commands
	g:atp_completion_truncate	= 4
		do not complete commands less than 4 characters (not counting
		the leading '\' if present). If 0 then complete all the
		defined commands. This only works in the expert mode.

								*g:atp_MathOpened*
>
     	g:atp_MathOpened		= 1
<		the default value is 1. With the default value expert mode
		completion will check if you are completing inside
		mathematical environment or not. Inside math environment only
		math commands are completed and outside math commands are
		disabled. This makes the set of completions more accurate. If
		you need non math command (like \textrm{}) inside math use non
		expert mode (see |atp-completion-non-expert-mode|)

								*g:atp_MathZones*
>
	let g:atp_MathZones	= [ 
	    		\ 'texMathZoneV', 	'texMathZoneW', 
	    		\ 'texMathZoneX', 	'texMathZoneY',
	    		\ 'texMathZoneA', 	'texMathZoneAS',
	    		\ 'texMathZoneB', 	'texMathZoneBS',
	    		\ 'texMathZoneC', 	'texMathZoneCS',
	    		\ 'texMathZoneD', 	'texMathZoneDS',
	    		\ 'texMathZoneE', 	'texMathZoneES',
	    		\ 'texMathZoneF', 	'texMathZoneFS',
	    		\ 'texMathZoneG', 	'texMathZoneGS',
	    		\ 'texMathZoneH', 	'texMathZoneHS',
	    		\ 'texMathZoneI', 	'texMathZoneIS',
	    		\ 'texMathZoneJ', 	'texMathZoneJS',
	    		\ 'texMathZoneK', 	'texMathZoneKS',
	    		\ 'texMathZoneL', 	'texMathZoneLS',
			\ 'texMathZoneT' ]
< 	the default value in plaintex files is >
	g:atp_MathZones	= [ 'plaintexMath' ] 
<		These are zones recognized by tab completion as mathematical
		ones (see |g:atp_MathOpened|).
>
	g:atp_tab_map
	g:atp_no_complete		= ['document']
<		List of environments which is not closed by <tab> completion.
		(The document environment in longer documents can be not seen
		by the algorithm as closed, because it searches only in a part
		of the text, see |g:atp_completion_limits| variable above).
>
	g:atp_bracket_dict 	= { '(' : ')', '{' : '}', '[' : ']', '<' : '>', 
		    \ '\lceil' : '\rceil', 	'\lfloor' : '\rfloor', 
		    \ '\langle' : '\rangle', 	'\lgroup' : '\rgroup' }
<		You can speed up Tab Completion by removing brackets that you
		don't use. >
	g:atp_sizes_of_brackets = {'\left': '\right', 		'\bigl' : '\bigr', 
				 \ '\Bigl' : '\Bigr', 		'\biggl' : '\biggr' , 
				 \ '\Biggl' : '\Biggr', 	'\' : '\' }
<
							*g:atp_LatexPackages*
							*g:atp_LatexClasses*
	The variables: >
	g:atp_LatexPackages
	g:atp_LatexClasses
<	stores list of packages and classes in your tex distribution. They are
	restored when you exit Vim from the global project script (see
	|atp-ProjectScript_global|).  They are used for completion of the LaTeX
	commands \usepackage and \documentclass.

	If you reinstall, add or remove tex classes/packages from your tex
	distribution it is enough to unlet these variables. ATP will find new
	values when it will need them for the first time. 


================================================================================
HOW TO CONFIGURE ATP TO YOUR NEEDS                      *atp-configure*
							*atp-variables*

There are several options you can set, and they might be set in your Vimrc
file. The default values are given below (except the completion setup and
bibtex documented above). Note: not all variables are listed below.

All the values of important variables with their values can be shown
(grepped) by |atp-:ShowOptions| command.

							*atprc*
$HOME/.atprc.vim (only on Unix and GNU/Linux) or 
$VIMRUNTIME/ftplugin/ATP_files/atprc.vim					
    A configuration file for ATP. You do not have to use autocommands to set
    local-buffer variables, just place them here. The settings in |atprc| file
    override the values in the project script (|atp-ProjectScript|). You can
    also overwrite the plugin maps there it you want to have different
    behaviour on the key map used by ATP. This file is source twice, before
    and after sourcing ATP.

Tip: If you want to see (almost) all the variables, type ':let g:atp_<CTRL_D>',
and ':let b:atp_CTRL-d'.

All buffer variables (see |b:var|), i.e. these which name begins with "b:",
should be set in your |vimrc| or |atprc| file. If you want to use your vimrc file
then the best way to do that is by using an autocommand:
>
	au BufReadPre *.tex let b:atp_TexCompiler="latex"
<
If you put just let |b:atp_TexCompiler|, this will also work but not always: for
example when you open a new buffer in existing Vim session. However, if you
put them in your |atprc| it is enough to use the standard "let b:...=".
							*b:atp_TexCompiler*
>
 let b:atp_TexCompiler	= "pdflatex"			
<	Used by functions: TEX() (map <LocalLeader>l, imap <LocalLeader>l),
	VTEX() (map <F5>, imap <F5>)

	You can set it to latex, tex, luatex, and so on and possibly to
	lilypond as well.  

	There is a command to set this variable with nice completion, see
	|atp-:Compiler|. 
							*b:atp_TexCompilerVariable*
>
 let b:atp_TexCompilerVariable = "max_print_line=2000" 	
<	You can use it to set an environment variables for the compiler. The
	"max_print_line" sets the maximal length of a line in the log file.
	The value 2000 is high enough to prevent line breaking.

	Note: the grammar for this variable: it should be a semicolon separated
	list of variables and values, i.e. 'variable_1=value_1;variable_2=value_2'
							*b:atp_BibCompiler*
>
 let b:atp_BibCompiler	= "bibtex"			
<	This variable sets the bibtex backend. There are other programs which
	might be used, for example biber and pybib (not tested with ATP).
	
	The default value will be "biber" if the preamule contains
	\usepackge[backend=biber]{biblatex}. If it is set to "biber" ATP will
	adjust |g:atp_keep| variable (add run.xml, bcf extensions) when you use
	|atp-:TEX|, |atp-:Bibtex|, or |atp-:MakeLatex| commands.

	Biblatex package allows for putting \bibliography{} type commands only
	in the preamble. Thus ATP will search for them only there. The
	|g:atp_inputfile_pattern| might not contain any pattern for
	bibliographies (\addbibresource, \bibliography, etc.). The
	|atp-:InputFiles| command will search for them in a special subroutine
	which only searches in the preamble. This makes it slightly faster.

							*b:atp_TexFlavor*
>
 let b:atp_TexFlavor	= "tex"	
<	If you are editing a plain tex file it is automatically set to
	'plaintex', then you get highlighting for $$:$$. Some other features
	are planned (you can also set this while editing a 'tex' file, i.e.
	latex document but using $$:$$ is latex is not recommended it is know
	to break some latex specific things).
							*b:atp_TexOptions*
>
 let b:atp_TexOptions	= "-synctex=1"			
<	This is a comma ',' separated list of TeX compiler options. If you
	want to set some additional options to your tex compiler you can use
	this variable, note that '-output-directory' and '-interaction' are
	set by ATP. 

							*b:atp_OutDir*
>
 let b:atp_OutDir	= fnameescape(fnamemodify(resolve(b:atp_MainFile,":h")) . "/"
<	This is the directory in which tex will put the output files. If the
	open file is not a symbolic link it is equal to the directory in which
	the tex file is located. If the open file is a symbolic link it points
	to the directory in which the real file is located. 
	
	If you set this variable to './' (or '.') and change the current
	working directory for example to /tmp (:cd /tmp) then the latex output
	will be placed in /tmp, i.e. it will move with with cd. However, the
	default value of b:atp_OutDir is not affected by :cd command.

	White spaces and other characters should not be escaped. It will be
	quoted in '...' using the |shellescape()| function.

	You can see the current output directory in the status (it is in the
	short notation) to see it whole type:
		:echo b:atp_OutDir
	or use the |atp-:ShowOptions| command.		

	If in your environment the variable $TEXMFOUTDIR is set the value of
	b:atp_OutDir will be set to its value.

							*b:atp_auruns*
>
 let b:atp_auruns	= 1				
<	This variable control how many times the automatic function calls tex
	compiler (consecutively). It is useful if you are working with PDF
	files and you want to have bookmarks (you can get them using hyperref
	package with the option: bookmarks. Then set b:atp_auruns to '2'.

							*b:atp_running*
>
 b:atp_running						
<	This variable stores the current number of running instances of latex.
	When it is greater than 1 a message in the status line is shown. If :PID
	command returns that no latex is running this variable this variable
	is reset to 0. 
							*g:atp_MathVimOptions*
>
 g:atp_MathVimOptions	= { 'textwidth' : '0' }
<	This variable is a dictionary of Vim settings and its values which
	will be valid when you edit mathematics inside the pairs \(:\), $:$,
	\[:\], $$:$$ (only in plain tex files or if g:atp_TexFlavour
	= 'plaintex').  For example, the default value will toggle between
	your 'textwidth' in non-math and 0 in math.  The dictionary may
	contain short option names equally well as long names.

	Note: the standard tex syntax file defines other zones: for example
	for align and equation environments (and many others) but some how
	they are not accessible using synstack() function. 
			
							*g:atp_SetMathVimOptions*
	This feature can be turned off setting variable >
			g:atp_SetMathVimOptions
<	to '0', the default is '1'.
							*g:atp_autex_check_if_closed*
>
 let g:atp_autex_check_if_closed = 1  			
<	This feature is not implemented.
	tex run if all environments \begin:\end, \(:\) and \[:\] are closed.
	Set g:atp_autex_check_if_closed=0 in order to not make the checks.
							*g:texmf*
>
 let g:texmf	= substitute(system("kpsewhich -expand-var='$TEXMFHOME'"), '\n', '', 'g')
<	This variable configures where local input files are placed. See
	|atp-:Edit|. Note: if you set this variable in |vimrc| or |atprc| file
	vim will startup a bit faster with tex files, since calling kpsewhich
	is slow.
							*g:askforoutdir*
>
 let g:askforoutdir	= 0				
<	Its values are 1 and 0.  When it is set to 1 you will be asked for the
	name of a directory where tex will put output files, note that this
	name should end with a "/".
							*b:atp_Viewer*
>
 let b:atp_Viewer	= "okular"			
<	it was tested with Xpdf, Evince, ePdfViewer, Kpdf, Okular, Xdvi and
	they all works fine. I'm using Xpdf and the Xpdf server options are
	supported so that the file is automatically reloaded (other viewers,
	except epdfview, have this functionality as well. This do not works
	for acroread. Read more about viewers in |atp-viewers|. 

	If you use program b:atp_Viewer then you can use the variable
	b:atp_{b:atp_Viewer}Options to set the options (it is a vim list), for
	example if b:atp_Viewer="xpdf" then you might use:

							*atp-Viewers_Options*
							*b:atp_xdviOptions*
    							*b:atp_xpdfOptions*
    							*b:atp_okularOptions*
    							*b:atp_evinceOptions*
    |b:atp_xpdfOptions|
    |b:atp_xdviOptions|
    |b:atp_okularOptions|
    |b:atp_evinceOptions|, etc ... (also global variables g:atp_...Options)
	Used by function: ViewOutput() (map <LocalLeader>v, map <F3>, imap <F3>)

	These are lists in which every viewer switch and its value should be
	placed as element (separate!). See examples below. 

	For example, if you want to have different look of one document you can
	set it to "-bg gray20". Some examples:
>
 	let b:atp_xpdfOptions	= ['-bg', 'Grey30', '-mattecolor', 'SlateBlue2', '-papercolor', 'White']
	let g:atp_xpdfOptions	= ['-bg', 'NavajoWhite4', '-fg', 'black', '-mattecolor', 'burlywood']
	let b:atp_xdviOptions	= ['-expertmode', '0', '-s', '6', '-watchfile', '1']
<	
							*g:atp_XpdfServer* 
>
 let b:atp_XpdfServer=fnamemodify(expand("%"),":t")		
<	This variables stores the name of Xpdf server (if you use xpdf to view
	pdf files).

	Used by the command |atp-:View| (map <LocalLeader>v, map <F3>, 
	imap <F3>) and also |atp-:SyncTex| (map <LocalLeader>f).

	You do not need escape spaces in the name (shellescape() function is
	used before it is send to the shell).
							*g:atp_LocalXpdfServer* 
>
 let b:atp_LocalXpdfServer=fnamemodify(expand("%"),":t")		
<	This variables stores the name of Xpdf server which will host compiled 
	subfiles.	
	
	Used by the command |atp-:ViewL| (map <LocalLeader>V, map <S-F3>, 
	imap <S-F3>) and also |atp-:SyncTexL| (map <LocalLeader>F).

	You do not need escape spaces in the name (shellescape() function is
	used before it is send to the shell).
							*b:atp_OpenViewer*	
>
 let b:atp_OpenViewer	= 1					
<	If the function which calls TeX compiler do not see that you are
	viewing the output file it will open it for you if b:atp_OpenViewer=1.
	Otherwise, this feature is disabled.
>
 let g:atp_delete_output	= 0
<	If set to 1 then Delete function (map <F6>d) will delete also the
	output file.	
							*g:atp_cpcmd*
>
 let g:atp_cpcmd		= "/bin/cp"
< 	This sets the copy command used by compiler. The value tries to not use
	shell internal function and to avoid the -i switch (ask if overwrite). 

							*g:atp_tex_extensions*	
>
 let g:atp_tex_extensions=["aux", "log", "bbl", "blg", "bcf", "run.xml", "spl", "snm", "nav", "thm", "brf", "out", "toc", "mpx", "idx", "maf", "blg", "glo", "mtc[0-9]", "mtc1[0-9]", "pdfsync" , "ind"]	
<
	 This list is used by the |atp-:Delete| command which deletes all the
	 files with the specified extension in the directory |b:atp_OutDir|.
							*g:atp_keep*			
>
 let g:atp_keep	= [ "log", "aux", "toc", "bbl", "ind", "idx", "synctex.gz", "blg", "loa", "toc", "lot", "lof", "thm", "out" ]
<	Files with an extension belonging to this list will be copied from
	'b:atp_OutDir' to the temporary directory with appropriate name. Then it
	will be used by (La)TeX. (log file will be copied after it is created,
	other files will be copied back and forth between 'b:atp_OutDir' and the
	temporary directory). These four elements: log,aux,toc,bbl are
	essentially minimum to work with: table of contents, pdf-bookmarks and
	bibtex. There are possibly other classes, like beamer, or packages
	like theorem (produce .thm files) which will need to configure this
	variable.

	If you use "biber" ATP will add "run.xml" and "bcf".

	You can change this variable by the command:
		:let g:atp_keep+=["spl"]
							*g:printeroptions*		
>
 let g:printeroptions	= ""				
<	You can set the printer options. These are options for the 'lpr'
	command, which will print the output file (pdf or dvi) this depends on
	the b:atp_TexCompiler that you use.
							*g:atp_TexCommand*
>
 g:atp_TexCommand						
<	This variable is for debugging purposes. It stores the last executed command to
	compile your document. It changes also when your compiler was run
	automatically. >
		:TEX
		:echo g:atp_TexCommand
		:TEX!
		:echo g:atp_TexCommand
<	It is read-only variable.	
							*b:atp_TempDir*
>
 b:atp_TempDir = b:atp_OutDir/.tmp
<	In this directory vim (or python) will make a temporary directory
	(with a unique name) to which output files will be put by your TeX
	compiler. This is done so to prevent overwriting the output file while
	the compilation is being done (this can cause problems when there are
	many TeX processes and the Viewer is accessing not yet compiled
	file). The output files are copied back to b:atp_OutDir after
	compilation. The temporary directory is passed to your TeX compiler
	using '-output-directory' switch.  
							*g:atp_TempDir*
>
 g:atp_TempDir 
<	In this directory the logs of ATP are stored. If vim has python support
	is created by python in most secure way available (readable only by
	the user) if not it is made using |mkdir()| vim function with 0700
	permissions.
							*g:atp_CompilersDict*
>
 let g:atp_CompilersDict 	= { 
		\ "pdflatex": ".pdf", 		"pdftex" 	: ".pdf", 
		\ "xetex" 	: ".pdf", 	"latex" 	: ".dvi", 
		\ "tex" 	: ".dvi",	"elatex"	: ".dvi",
		\ "etex"	: ".dvi", 	"luatex"	: ".pdf"}
<	This variable is used to associate an extension to the compiler that
	is used.


g:defaultbibflags		see |atp-bibflags:default|
g:defaultallbibflags		see |atp-bibflags:all|
b:atp_LastBibFlags		see |atp-bibflags:last|

b:bibfiles			see |atp-variables-bib|
s:bibfiles
s:allbibfiles
s:notreadablebibfiles
	For more on bib flags see |atp-bibflags|.
>
 let t:toc_window_width=g:atp_toc_window_width
<	t:toc_window with is set to g:atp_toc_window_width (by default is 30)
	The global variable configures the initial width of the window with
	table of contents.
>
 let t:labels_window_width=30
<	g:labels_window_width (by default not set, if set overrides
	t:labels_window_width)
	Configures the initial width of the window with labels.
>
 g:atp_statusline
<	by default it is not set, put the line
>
	let g:atp_statusline=0
<
	in your |vimrc| or |atprc| file if you do not want the status line provided by this
	plugin. (See |atp-:Status|).
>
 let b:atp_TruncateStatuSection=40
<	This variable sets how many characters of the section/subsection title
	(or chapter/section titles if you write a book) should be shown in the
	status line.  Section title and subsection title gets equal amount of
	characters.
>
 g:atp_kpsewhich_tex	
 g:atp_raw_kpsewhich_tex
<	This two variables stores the information returned by 
	    'kpsewhich -show-path tex'
	They are locked. The first one has pretended '**' wild cards to every
	directory, which is done for using with globpath() and findfile()
	functions.

  							*g:atp_VimCompatible*
>
 g:atp_VimCompatible variable
<   	with default value 0 ("no"). Its values are 0/1 or yes/no. It changes 
	the behaviour of '%'. In nocomatible mode it goes to matching pair
	in a different line in compatible mode it finds the matching pair only
	if the ending bracket is in the same line.
	See also how it changes the behaviour of |atp-]%| and |atp-[%|.

							*g:atp_indent*
>
 g:atp_idnent=1
<	by defalt ATP is useing LatexBox indentation script. If you set this
	to 0 the vim runtime indantation script will be used. Also
	'indentkeys' differ.


================================================================================
WRITING PROJECTS					*atp-ProjectFiles*
							*b:atp_MainFile*
>
 let b:atp_MainFile	= expand("%:p")
<	This variable points to the main file of the project, it is set on the
	start up to the file you open. If you edit project file (for the first
	time), start with the main file and use gf (see |atp-gf|) to go to the
	project file you want to edit. In this way all the project files will
	have correctly set this variable. The value of this variable is used
	by compilation functions. This variable is written in the project
	script (see |atp-ProjectScript|). And when the project script is on (see
	|atp-ProjectScript|, or set |b:atp_ProjectScript|=1) it is restored between
	sessions. In this way, next time, you can open any project file and
	the b:atp_MainFile variable will be set to the correct value.

							*b:TreeOfFiles*
							*b:ListOfFiles*
							*b:TypeDict*
							*b:LevelDict*
	The project feature stores more variables: |b:TreeOfFiles| a dictionary
	which contains the tree of input files, |b:ListOfFiles| - list of input
	files, |b:TypeDict| dictionary of types of input files, where the type
	is one of following: {preamble}, {input}, {bib}. The last variable is
	|b:LevelDict| which is a dictionary of input levels (for example: an
	input file in input file has level 2).

	There are other tools to make editing project files more easy. There
	is search function: |atp-:S| which works better than the Vim |:ijump|
	command, which cannot go above the current file in the tree of input
	files /but |:ijump| is much faster/. 

	If you write a project you might want to use subfiles package. Then
	you can compile with |atp-:TEXL|, view with |atp-:ViewL| and forward
	search with |atp-:SyncTexL|. Furthermore, you can still use completion
	of labels by numbers if you add to the preambule of the subfile the
	following command (requires ifthen package): >
	    \ifthenelse{\value{chapter}=0}{\setcounter{chapter}{CHAPTER_NR}}{}
<	This command will manually set the chapter number to CHAPTER_NR.
	However, when you compile the whole project this command will not
	affect the project.

*b:atp_ProjectDir*
	Stores the project directory, by default where |b:atp_MainFile| is
	located (the filename is resolved if it is a symbolic link). It is not
	written to the |atp-ProjectScript| (this makes the |atp-ProjectScript|
	independent of the host when |g:atp_RelativePath| is set). This
	variable is mainly for internal purposes. If you want to set the
	output directory use |b:atp_OutDir|.

*g:atp_RelativePath*
	If set to 1 (which is the default), project variables: |b:atp_MainFile|,
	|b:TreeOfFiles|, |b:ListOfFiles|, |b:TypeDict|, |b:LevelDict| will store path
	relative to |b:atp_ProjectDir| (which is the same as path to your main
	file, however if the file is a symbolic link it will hint to the
	resolved path). The |atp-:S| will use correctly these values. This is
	particularly useful if you want to share the project file.
	 
	If you run into problems with |atp-:S| you can set this variable to
	0 and use |atp-:InputFiles| to regenerate the variables - they will
	now store the full path (the other way around also works).

:ToggleNn [on]						*atp-:ToggleNn*
	The command |atp-:ToggleNn| toggles the value of |g:atp_mapNn| variable.
	The optional argument [on] has three possible values: "",  "on" or
	"off".  The default "", toggles the value of |g:atp_mapNn|, "on" sets
	g:atp_mapNn to 1 and "off" sets it to 0.
							*g:atp_mapNn*
>
 g:atp_mapNn = 0
<	If it is set to 1 then several tools use |atp-:S| command instead of
	Vim |search()| function (which looks only in the current buffer).
	These are: 
	|atp-:NPart|, |atp-:NChap|, |atp-:NSec|, |atp-:NSSec|, |atp-:NSSSec|, 
	|atp-:PPart|, |atp-:PChap|, |atp-:PSec|, |atp-:PSSec|, |atp-:PSSSec|, 
	|atp-:NEnv|,
	|atp-:PEnv|.

	The default value of |g:atp_mapNn| is 0.

	The variable g:atp_mapNn should be always set as follows (in
	|atprc| or |vimrc| file): >
		if !exists("g:atp_mapNn")	
		    let g:atp_mapNn = 1
		endif
<	Then the value will be preserved when atp opens new buffer 
	when using |atp-:S| command. If you want to have project specific
	setting use |atp-ProjectScript|.

	Another good tip for LaTeX project files is to set |b:atp_TexFlavor|
	variable to 'tex' (in your |vimrc| or |atprc| file). This will prevent
	from situations that Vim recognizes input file as a plain TeX while it
	is an input file into a LaTeX project. 
	Another way is add options to 'viewoptions' (see |'viewoptions'|). And
	set mkview and loadview via autocommands >
		au BufWinLeave *.tex mkview
		au BufWinEnter *.tex silent loadview
<	This will ensure that filetype variable is set correctly. Some ATP tools
	behave in a different way in plaintex files. For example TreeOfFiles
	function (it makes the variables |b:TreeOfFiles|, |b:ListOfFiles|,
	|b:TypeDict|, |b:LevelDict|). It is recursive in LaTeX files but not in
	plain TeX files). On this function is based the command
	|atp-:LocalCommands| which makes list of commands, environments and
	colours for Tab Completion and also |atp-:S| command. It is done so,
	because in plain tex there is no way to distinguish input files from
	input packages which we do not want to scan (especially recursively,
	which might be time consuming). 

PROJECT SCRIPT						*atp-ProjectScript*
    LOCAL PROJECT SCRIPT ~
<	The file: |b:atp_MainFile| . ".project.vim", called local project
	script, in the same directory as |b:atp_MainFile| stores values of
	variables saved before Vim left the  buffer (it is very similar to
	|View|). It is a configuration script per project. There is additional
	file which stores some global variables, see
	|atp-ProjectScript_Global|.
	
	Loading procedure searches for files which ends with '.project.vim'. There
	might be many such files in one directory. The file is used which contains
	the current buffer in the list |b:ListOfFiles| or as a value of
	|b:atp_MainFile|. If there wasn't any such the project scripts file
	then a new project script will be written for the current buffer. Before
	writing the project script file if |b:ListOfFiles| doesn't exists it
	will be generated and written.

	The project script is stored locally so that it is possible to include
	it in a revision system (git, bzr, svn, etc.) and share it with
	collaborators.

	The variable |g:atp_ProjectLocalVariables| stores the names of
	variables written to the local project script, similarly the varaible
	|g:atp_ProjectGlobalVariables| is a list of variables stored in the
	global project file.

	The |atprc| file (and tex.vim file in after/ftplugin/ directory) is
	executed after the global project script and before the local one.
	(Precisely all the |:let| statements are executed before |atprc| file
	but all the |:set| and |:setl| statements are executed afterwards).
	The |:set| and |:setl| statements are executed only once (per project
	file).

	If you want to have two main files (for example a copy of a project
	in another directory below the project main directory), i.e.
	    main.tex
	    tmp/main.tex
	Then the easiest way is to open tmp/main.tex and adjust the variables:
	|b:atp_ProjectScriptFile| to point to tmp/main.tex.project.vim and
	|b:atp_MainFile| (this is necessary only if |g:atp_RelativePath|=0)
	and run |atp-:InputFiles|, then use |atp-:WriteProjectScript|.


							*b:atp_ProjectScript*
							*g:atp_ProjectScript*
	Setting one of the variables |b:atp_ProjectScript| or
	|g:atp_ProjectScript| to 0 the feature will be turned off. Local
	variable, i.e. b: has precedence over the global one g:. So you can
	turned off the feature for only specific files. The global variable
	will turn it off for all files.

							*g:atp_ProjectLocalVariables*
	Local and global variables can be stored in the local project script.
	The variables which are cached in local project script are listed in:
>
    let g:atp_ProjectLocalVariables = [
		\ "b:atp_MainFile", 	"g:atp_mapNn", 		"b:atp_autex", 
		\ "b:atp_TexCompiler", 	"b:atp_TexOptions", 	"b:atp_TexFlavor", 	
		\ "b:atp_auruns", 	"b:atp_ReloadOnErr", 	
		\ "b:atp_OpenViewer", 	"b:atp_XpdfServer",
		\ "b:atp_Viewer", 	"b:TreeOfFiles",	"b:ListOfFiles", 	
		\ "b:TypeDict", 	"b:LevelDict", 		"b:atp_BibCompiler", 
		\ "b:atp_StarEnvDefault", 	"b:atp_StarMathEnvDefault", 
		\ "b:atp_updatetime_insert", 	"b:atp_updatetime_normal"
		\ ] 
<
	If you want to alter value of this variable, it should be done in
	|atprc| or |vimrc| files. When you remove a variable from this list it
	will not automattically be removed from the local project script. You
	need to delete it your self (or delete the project script with
	|atp-:DeleteProjectScript|).

	If your vim doesn't have python support |+python| three more variables
	are stored: |b:atp_LocalEnvironments| |b:atp_LocalCommands|, and
	|b:atp_LocalColors|. With |+python| this is not needed since
	|atp-:LocalCommands| is then very fast and is run on |BufEnter|.

							*b:atp_ProjectScriptFile*
>
    let b:atp_ProjectScriptFile = b:atp_MainFile.".project.vim"
<	This variables stores the name of the current local project script file.

							*atp-ProjectScript_Global*
    GLOBAL PROJECT SCRIPT ~
	There is also file for variables for all projects. It stores values of
	global variables (by default it is "ftplugin/ATP_files/common_var.vim". 
	The global variables that are written in this file are given in Vim
	list: 
    							*g:atp_ProjectGlobalVariables*
>
		let g:atp_ProjectGlobalVariables = [ 
			\ 'g:atp_LatexPackages', 	
			\ 'g:atp_LatexClasses', 
			\ 'g:atp_Library' ]
<
	If you want to disable this feature for some reason you can set: >
		let g:atp_ProjectScript = 0
<	or >
		let b:atp_ProjectScript = 0
<	if you want to disable this feature only for a given buffer. 
	(The value of local variable overrides the value of global one!).
	Hint: (if you want to disable loading project script for one file): 
	    In your .vimrc file you can set the local variable via
	    autocommand group BufEnter or you can put an if statement in your
	    |atprc| file: >
		if expand("%:p") == <path_to_file>
		    let b:atp_ProjectScript = 0
		endif
<	    or you can add to the project scrpit: 
		 (1) write in its first line 'finish', or
		 (2) include in it 'let |b:atp_ProjectScript| = 0'.

	There are these commands: ~
:LoadProjectScript[!] [local/common]			*atp-:LoadProjectScript*
:WriteProjectScript[!] [local/common]			*atp-:WriteProjectScript*
:DeleteProjectScript[!] [local/common]			*atp-:DeleteProjectScript*
:ToggleProjectScript[!] [on/off]			*atp-:ToggleProjectScript*

	which do the obvious thing (if |g:atp_ProjectScript|=0 or |b:atp_ProjectScript|=0 they
	will not work). The default value of the optional argument is "local".
	:DeleteProjectScript [local] command (with optional argument [local]) deletes
	the project script file for the current buffer (only the local one), with
	bang "!" it deletes also global project scrip. The bang of
	:WriteProjectScript forces to write to project script even when
	project script is turned off (|b:atp_ProjectScript|==0 or
	!exists("|b:atp_ProjectScript|") && |g:atp_ProjectScript|==0).

	The command ':ToggleProjectScript [on/off]' turns on/off the feature
	for this buffer (it sets |b:atp_ProjectScript|). When no argument is
	given it will toggle the value. With bang it also sets the global
	variable |g:atp_ProjectScript|. |b:atp_ProjectScript| is by default in the >
	    g:atp_ProjectLocalVariables 
<	so it will be restored afterwards. |b:atp_ProjectScript| if defined
	overrides the value of global variable |g:atp_ProjectScript|. So you can set
	in your atp file g:atp_ProjectScript = 0 and for some files using the
	if-construction: >
		let g:atp_ProjectScript = 0
		if expand("%:t") == "myfile.tex"
		    let b:atp_ProjectScript = 1
		endif
<	will turn on the feature only for myfile.tex. Something more elaborate
	would be to set |b:atp_ProjectScript| only for files with modification time
	less than two days for example.

	Note: If you delete the project script for the current buffer it will be
	written after exiting Vim, unless you turn off the project feature.

	The project script is disabled for files which full path matches
	"texmf".  With the optional bang |atp-:LoadProjectScript| loads the
	common project script also for them. |atp-:WriteProjectScript| command
	will write the project script disregarding if the file is under texmf
	directory or not.

	Note: If you use this feature, you might need to use the commands:
	|atp-:LocalCommands| and |atp-:InputFiles| which will update
	b:atp_LocalCommands, b:atp_LocalColors, b:atp_LocalEnvironments and
	|b:TreeOfFiles|, |b:ListOfFiles|, |b:TypeDict| and |b:LevelDict|. Use
	these commands with a bang "!". The second set of variables is also
	updated by |atp-:S| (also with "!") and and |atp-:GotoFile| (with "!"
	as well).

	Note: Also when you add a package to tex you should remove the common
	project scrip, so that the new packages will be added to completion
	list. 

							*atp-:S*
:S[!] /{pattern}/ [flags]
	The pattern is a Vim pattern (with 'magic'). With bang "!" it
	regenerates the tree of input files.

	This is command does the same job as |/| but is recursive in the tree
	of files (so it is useful only in project files). The syntax of this
	command is similar to |:vimgrep|. 

	This works similarly to |:ijump|. But also goes back to the root file
	(b:atp_MainFile).

	Note: this command is very fragil on the variable b:TreeOfFiles. It
	should be uptodate if you use it (use the bang :S! or
	|atp-:InputFiles| command).

	It sets the alternate file to the buffer from which the search begun.
	Note that this means that if nothing was found the alternate file
	before search will be lost.

	Note: if 'shortmess' option contains 's' flag then 'Search hit BOTTOM
	...' and 'Search hit TOP ...' messages are not shown.

	The {pattern} is any Vim pattern as described in |pattern| (it was only
	tested with 'magic' set on).
			
	The supported [flags] are 'bcewWx'. Their meaning is the same as flags
	for |search()| function, except the additional flag 'x'. When used the
	|v:searchforward| value will not be changed.

	You can enclose the pattern with any non-ID character (see
	|'isident'|) instead of /, as far as it does not appear in the
	{pattern}. Examples: >
			    :S pattern\_swith\_sspaces
<	will work but: >
			    :S pattern with spaces
<	will not.		

	Note that the function might be slow when the project files where not
	yet opened.

	There is a function to check where the input file is on the hard drive
	if the name in the input command doesn't include the full path.  It
	asks kpsewhich which directories to search, filters out 
	directories which are not under '/home' (I assume that there is your
	local texmf tree) and also directories which name contains one of the
	two keywords 'texlive' and 'kpsewhich'. This makes the searching
	faster. 
							*atp-:S_input*
	Furthermore, the command is designed so that it can find all patterns
	'\\input' (and thus easily find next/previous input file). You can
	use: >
		:S \\input
		:S \\input b 
<	and you can use |n| and |N| Vim normal commands. 
	Note that it if you go backward, then it means that it will find the
	most deep line, e.g.:
>
		file.tex
			----
			----
			\input{file.1} ---->  -------
					      -------
					      \input{file.1.1}
					      -------
	                ----X	 			      
<	':S /\\input/ b' in the X position fill find \input{file.1.1} assuming 
	file.1.1.tex does not include any other files. 

							*atp-:NInput* 	*atp->i*   *atp->gf*
							*atp-:PInput* 	*atp-<i*   *atp-<gf*
	Now it also doesn't search inside commented input files. There two
	commands:
:NInput, nmap ]gf, nmap >i
:PInput, nmap [gf, nmap <i
	which finds the next/previous input line (also commented). See
	|atp-:S_input| to find how it works. They depend on |g:atp_mapNn|, if
	1 |atp-S:| is used if 0 Vim |search()| function. To repeat search you
	can use |n| and |N| Vim normal commands. These commands omit comment
	lines.

================================================================================
MAPS 		                     			*atp-mappings* 
							*atp-maps*

Lots of mappings which are given here uses #. This is a convenient map on
British keyboards, but not in the US layout, you can change them for '`' or
some other key that it is not used in Vim (there are not many of them though).
The most commonly used latex-suite plugin uses similar set of mappings (but
there might be some differences). The easy way to change imap leaders is by
using the variables:
							*g:atp_imap_leader_1*
>
	    g:atp_imap_leader_1 = "#"
<	    	for Greak letters and some math commands,
							*g:atp_imap_leader_2*
>
	    g:atp_imap_leader_2 = "##"
<	    	for font commands, (another good choice is "_") 
							*g:atp_imap_leader_3*
>
	    g:atp_imap_leader_3 = "]"
<	    	for environments, 
							*g:atp_imap_leader_4*
>
	    g:atp_imap_leader_4 = "["
<	    	for extra environments in the old layout (this will be removed).
							*g:atp_imap_over_leader*
>
	    g:atp_imap_over_leader = "`"
<		for imaps of all sort of accents. See |atp-imaps-diacritics|,
		some maps in |atp-imaps-math-misc|, and also in vmaps:
		|atp-vmap-WrapSelection-accents|.
							|g:atp_map_forward_motion_leader|
>
	    g:atp_map_forward_motion_leader = ">"
<		for maps to |atp-:NInput|, |atp-:NSec|, .... , |atp->E|, |atp->e|.
							|g:atp_map_backward_motion_leader|
>
	    g:atp_map_backward_motion_leader = "<"
<		for maps to |atp-:PInput|, |atp-:PSec|, .... , |atp-<E|, |atp-<e|. 


Note: the best way to search for (insert) maps is to use the |atp-:Imap|
command.

If you want change the map the best way is to copy the rhs of map provided by
ATP, since before loading maps the script tests if map to such rhs already
exists. To see it you can use on of '|:map| {lhs}<CR>' commands.

You can list imaps with |atp-:HelpMathIMaps| and |atp-:HelpEnvIMaps| but the
best way is to use |imap| directly.

All other mappings (|map|, |vmap|, |nmap|, ...) are using |<LocalLeader>| which can be
altered with the option |maplocalleader|. A good alternate solution is to use "_"
instead of "##".

Maps are using the <buffer> option thus are local to the buffer. To unmap you
also have to use this option, for example to unmap <LocalLeader>l issue the
command:
>
	:unmap <buffer> <LocalLeader>l
<
The maps are loaded unless you set one of variables: 'g:no_plugin_maps' or
'g:no_atp_maps' (disables maps defined in tex_atp.Vim), 'g:no_atp_toc_maps'
(disables maps defined in 'toc_atp.Vim'),  'g:atp_no_env_maps' (disables the
environment maps '[*', ']*') or |g:atp_tab_map| (disables the tab map
for completion, then completion is mapped to <C-X><C-O> and <C-X>o (for the non
expert mode) but there is no map for 'WrapSelection()', you have to provide 
one by your self).

Note: in all mappings '\' is set to your |<LocalLeader>| (and thus, in fact, the
maps listed below might differ).

Note: The list of commands might not be complete.

Note: There are many internal maps defined |<Plug>|, they are not documented,
but you can easily find them (you can start with
ftplugin/ATP_files/mappings.vim, where they are used in rhs of maps or you can
search for them inside the scripts). 

Note: you might like to use |'notimeout'| and |'nottimeout'| settings.
However, they require that there are no maps such that no lhs is a subset ot
the another, i.e. like "ab" and "abc". With the default settings it is
shouldn't be a problem.

							*atp-]]*
nmap ]], vmap ]]
	Goto next \begin{

							*atp-[[*
nmap [[, vmap [[
	Goto previous \begin{

							*atp-][*
nmap ][, vmap ][
	Goto next \end{

							*atp-[]*
nmap [], vmap []
	Goto previous \end{

							|atp-gc|
nmap gcl, vmap gc 
	Goto end of comment group (current or next if not in comment).

							|atp-gC|
nmap gC, vmap gC
	Goto begin of comment group (current or previous if not in comment).
	    
							*atp-comment-lines*
							*atp-uncomment-lines*
							*g:atp_MapCommentLines*
nmap <LocalLeader>c, vmap <LocalLeader>c   -- comment
nmap <LocalLeader>u, vmap <LocalLeader>u   -- uncomment
	Comment/Uncomment lines (both in |Normal| and |Visual| modes). 

	Comment leader can be set with the variable g:atp_CommentLeader (by
	default it is '% '). If you do not want this maps or you want to
	remap them to something else you can set |g:atp_MapCommentLines|=0 in
	your |vimrc| or |atprc| file and use <Plug>CommentLines,
	<Plug>UnCommentLines (these are normal maps), for example:
		nmap <LocalLeader>C 	<Plug>UnCommentLines
		vmap <LocalLeader>C 	<Plug>UnCommentLines
	A useful map for uncommenting |atp-_c| (i.e. |atp-select-comments|).

							*atp-<space>*
cmap <buffer> <C-Space> 	\_s\+
cmap <buffer> <C-_> 		\_s\+
    The <C-Space> map doesn't work in Vim, instead <C-@> is used which works
    as <C-Space>. In Vim, and gVim as well. See |atp-:ToggleSpace|.


IMAPS 							*atp-imaps*
All ATP imaps ae defined in several variables (vim lists): >
 g:atp_imap_greek_letters 
 g:atp_imap_math
 g:atp_imap_math_misc,
 g:atp_imap_diacritics
 g:atp_imap_environments
 g:atp_imap_fonts.
< Itmes of this vim lists are vim list of the following form:
[ <imap_command>, <imap_args>, <imap_leader>, <imap_lhs>, <imap_rhs>, <info> ]
The first four lists: g:atp_imap_greek_letters, g:atp_imap_math,
g:atp_imap_math_misc, are only defined when you enter LaTeX math mode. For
example by typing '\(' or '\begin{align}', etc ... (this is recognized using
syntax: |synstack()|). The imap defined in g:atp_imap_diacritics are only
defined in non math mode. The advantage of this is that the imap o* which
produces \otimes doesn't affect typing o in LaTeX text mode. In this way we
can provide many useful math imaps!

The function which makes the imaps is: atplib#MakeIMaps(), the function which
toggles on/off math/text imaps is atplib#ToggleIMaps() (which now also set vim
options for math mode, see |g:atp_MathVimOptions|).

NOTE: If you are looking for some imap, using :imap you might not find it,
because some imaps are only defined when ATP is in insert mode. Moreover, the
result depends if you are in a mathematical environment or not. Here is
a trick how to find an imap which is only defined in insert mode. First go to
insert mode, then press CTRL-O (see |i_CTRL-O|), and then type ':imap<CR>'.
If the cursor sands inside mathematical environment (for example inside \[:\])
the result will show mathematical imaps. This is especially useful tip for imaps
which begins with ' - different imaps for accents in LaTeX text and math
modes.

							*atp-j_motion* *atp-k_motion*
imap CTRL-j, imap CTRL-k	- these are two motions (based on syntax)
which help to navigate thought brackets (but not only) in insert mode.
   
map CTRL-j, map CTRL-k	 	- as above but in normal mode.

	These motions emulate the behaviour of latex-suite place holder system <++>,
	without putting the placeholder into tex file.

FONT COMMANDS						*atp-imap-fonts*

Below are listed font imaps. They work in text mode, or math mode, or if there
is only one given in both. The map leader is defined by the variable
|g:atp_imap_leader_2|, which by default is set to '##' (another good
setting is '_')
	  	in text			in math ~
imap <LocalLeader>rm 	\textrm{}<Left>		\mathrm{}<Left>
imap <LocalLeader>te 	\textrm{}<Left>		\text{}<Left>
imap <LocalLeader>up	\textup{}<Left>
imap <LocalLeader>md	\textmd{}<Left>
imap <LocalLeader>sl	\textsl{}<Left>
imap <LocalLeader>sc	\textsc{}<Left>
imap <LocalLeader>em	\emph{}<Left>
imap <LocalLeader>it 	\textit{}<Left>		\mathit{}<Left>
imap <LocalLeader>sf 	\textsf{}<Left>		\mathsf{}<Left>
imap <LocalLeader>bf 	\textbf{}<Left>		\mathbf{}<Left>
imap <LocalLeader>bf 	\texttt{}<Left>		\mathtt{}<Left>
imap <LocalLeader>no	\textnormal{}<Left>	\mathnormal{}<Left>
imap <LocalLeader>bb	\(\mathbb{}<left>	\mathbb{}<Left>
imap <LocalLeader>cal	\(\mathcal{}<left>	\mathcal{}<Left>
imap <LocalLeader>cr	\(\mathscr{}<left>	\mathscr{}<Left>
imap <LocalLeader>fr	\(\mathfrak{}<left>	\mathfrak{}<Left>

							*atp-nmap-fonts*
These maps are also defined in normal mode. They requre a motion afterwards,
i.e. <LocalLeader>rmw will wrap next word in \textrm{:} or \mathrm{:}.

							
GREEK LETTERS						*atp-imap-greek-letters*
Note: You can list this mappings using the command |atp-:HelpMathIMaps|. You
      might not see them using |:imap| unless the last cursor position in
      insert mode was inside mathematics.
							*g:atp_imap_define_greek_letters*
Note: If you do not want imaps for greek letters you can set
      |g:atp_imap_define_greek_letters| = 0
Note: |g:atp_imap_leader_1| is used as a leader (with the default value '#').
Note: if the previous character is '\' the mapping will not work which allows
      writing '\#a', etc. However, there is no check for '\\'.
imap #a 	\alpha
imap #b 	\beta
imap #c 	\chi
imap #d 	\delta
imap #e 	\epsilon
imap #ve	\varepsilon
imap #f 	\phi
imap #vf	\varphi
imap #y 	\psi
imap #h 	\eta
imap #k 	\kappa
imap #l 	\lambda
imap #i 	\iota
imap #m 	\mu
imap #n 	\nu
imap #p 	\pi
imap #o 	\theta
imap #vo 	\vartheta
imap #r 	\rho
imap #s 	\sigma
imap #vs 	\varsigma
imap #t 	\tau
imap #u 	\upsilon
imap #vp	\varpi
imap #w 	\omega
imap #x 	\xi
imap #z 	\zeta

Not all upper Greek letters are in LaTeX:
imap #D 	\Delta
imap #Y 	\Psi
imap #F 	\Phi
imap #G 	\Gamma
imap #L 	\Lambda
imap #M 	\Mu
imap #P 	\Pi
imap #O 	\Theta
imap #S 	\Sigma
imap #T 	\Tau
imap #U 	\Upsilon
imap #W 	\Omega

ENVIRONMENT IMAPS					*atp-imap-environments*
							*g:atp_imap_ShortEnvIMaps*
g:atp_imap_ShortEnvIMaps=1 
    By default the short environment imaps are defined, but if you set this
    variable to 0 you will get three letter abbreviations.  The only clashes
    is for proof (pro) and proposition (Pro) environments and itemize (ite)
    and \item (I). You can also reconfigure them using the variables:
    g:atp_imap_{env_name} (for example g:atp_imap_theorem, if you don't want
    a map for particular environment set the corresponding variable to empty
    string ""), |g:atp_imap_leader_3| is used as a leader (the default is
    ]).  Map for letter environment is not defined when you use short imaps.

Note: you can list this mappings using the command |atp-:HelpEnvIMaps|.
Note: This can be effectively set only in |atprc| or |vimrc| files.

    These maps are fully customizable: both sides: the lhs and rhs side ! Here
    is how you can set the rhs:
							*g:atp_EnvNameCorollary*
							*g:atp_EnvNameDefinition*
							*g:atp_EnvNameExample*
							*g:atp_EnvNameLemma*
							*g:atp_EnvNameNote*
							*g:atp_EnvNameProposition*
							*g:atp_EnvNameRemark*
							*g:atp_EnvNameTheorem*
    This variables defines environment names put it the following environment imaps.

							*b:atp_StarEnvDefault*
    b:atp_StarEnvDefault variable with value "*" or "" (the default). This
    star is added to theorem like environment imaps (|atp-imap-environments|).
    By default it will be restored by the project script. See
    |g:atp_ProjectLocalVariables|.

    							*b:atp_StarMathEnvDefault*	
    b:atp_StarMathEnvDefault variable with values "*" or "" (the default).  It
    is added to align and equation imaps (|atp-imap-environments|).  By
    default it will be restored by the project script. See
    |g:atp_ProjectLocalVariables|.

imap ]b   ]beg 		\begin{}<Left>
imap ]e   ]end		\end{}<Left>
imap ]C   ]cen 		\begin{center}<Cr>\end{center}<Esc>O

imap ]d   ]def 		\begin{definition}<Cr>\end{definition}<Esc>O
imap ]t   ]the 		\begin{theorem}<Cr>\end{theorem}<Esc>O
imap ]P   ]Pro		\begin{proposition}<Cr>\end{proposition}<Esc>O
imap ]l	  ]lem 		\begin{lemma}<Cr>\end{lemma}<Esc>O
imap ]r   ]rem 		\begin{remark}<Cr>\end{remark}<Esc>O
imap ]c   ]cor 		\begin{corollary}<Cr>\end{corollary}<Esc>O
imap ]p   ]pro		\begin{proof}<Cr>\end{proof}<Esc>O
imap ]x   ]exa 		\begin{example}<Cr>\end{example}<Esc>O
imap ]n   ]not 		\begin{note}<Cr>\end{note}<Esc>O

imap ]E   ]enu 		\begin{enumerate}<Cr>\end{enumerate}<Esc>O
imap ]I   ]ite 		\begin{itemize}<Cr>\end{itemize}<Esc>O

imap ]i   ]I		\item					*atp-item*
	This map has more features: if the preceding line is of the form:
		\item[(1)]
	then using this map in a next line will result with
		\item[(2)]
	This will work for other types of items, (1) -> (2), 1) -> 2),
	[1] -> [2], 1. -> 2. and also (a) -> (b), b) -> c), [c] -> [d],
	but also (1a) -> (1b). 
			

imap ]a   ]ali 		\begin{align}<Cr>\end{align}<Esc>O
imap ]q   ]equ 		\begin{equation}<Cr>\end{equation}<Esc>O

imap ]L   ]lef 		\begin{flushleft}<Cr>\end{flushleft}<Esc>O
imap ]R   ]rig 		\begin{flushright}<Cr>\end{flushright}<Esc>O

imap ]T   ]tik 		\begin{center}<CR>\begin{tikzpicture}<CR><CR>\end{tikzpicture}<CR>\end{center}<Up><Up>
imap ]f   ]fra 		\begin{frame}<Cr>\end{frame}<Esc>O

imap      ]let		\begin{letter}{<cursor>}
			    \opening{g:atp_letter_opening} 
			    \closing{g:atp_letter_closing}
			\end{letter}
							*g:atp_letter_opening*
							*g:atp_letter_closing*
    By default g:atp_letter_opening and g:atp_letter_closing are ''.


Next three sets of imaps: |atp-imap-math|, |atp-imap-math-misc| and
|atp-imap-diacritics| define imaps with overlapping keys (lhs), but note that
first two are defined only in math environment, while the last only in non
math environment. In this way `' in math environment will produce \acute{}
while in non math \'{}. 

 							*atp-imaps-math-misc*
							*g:atp_imap_math_misc*
MATH IMAPS MISC						*g:atp_imap_define_math_misc*

    These imaps are defined in |g:atp_imap_math_misc| variable (except ]m and ]M
    imaps). They might be turned off using |atp-:ToggleIMaps| commands or
    by setting |g:atp_imap_define_math_misc| variable to 0 (this should also
    work on the fly).

    These are very useful mappings for typing mathematics.  Some of the ideas
    were taken from TeX_9 by Elias Toivanen and also AuTeX by Carl Mueller.

    Note: you might not see them using |:imap| unless the last cursor position in
	  insert mode was inside mathematics.

AuTeX maps: ~
imap __ 	_{}<Left>
imap ^^		^{}<Left>
    You can set the leader for these two maps using g:atp_imap_subscript,
    g:atp_imap_supscript variables. If you do not have any maps which begins
    with _ or ^ then you can set them to _ and ^, if this is the case the
    maps will not be fired if you type \_ or \^ (which means literal _ or ^ in
    LaTeX). 

imap ]m 	\(\)<Left><Left>
imap ]M 	\[\]<Left><Left>

imap #\		\setminus
imap #/		\frac{}{}
imap #&		\wedge
imap #N		\Nabla
imap #=		\equiv
imap `8		\infty		[the default '#' is not working, ` is used instead, 
				 but only if |g:atp_imap_leader_1|='#']
imap `6		\partial	[as above, you can also use \p<Tab>]
imap `D 	<Esc>vxi\frac{\partial}{\partial "}
				[ let me explain the above map: you type x`D
				and you get \frac{\partial}{\partial x} ]
imap #@		\circ
imap #*		\bigcap
imap #+		\bigcup
imap #\		\backslash
imap #.		\dot		[#.s will put \dots]

MATH ACCENTS AND DECORATIONS ~

These imaps are defined in g:atp_imap_math_misc variable. They might be turned
off using |atp-:ToggleIMaps| commands or |g:atp_imap_define_math_misc| variable.

imap ``		\grave{}
imap `'		\acute{}
imap `>		\vec{}
imap `.		\dot{}
imap `v		\check{}
imap `_		\bar{}
imap `~		\tilde{}	[if g:atp_imap_wide is nonempty it is \widetilde{}]
imap `^		\hat{}		[as above]
imap `u		\underline{}
imap `o		\overline{}


 							*atp-imaps-math*
							*g:atp_imap_math*
MATH IMAPS						*g:atp_imap_define_math*

    These imaps are defined in |g:atp_imap_math| variable (except ]m and ]M
    imaps). They might be turned off using |atp-:ToggleIMaps| commands or
    |g:atp_imap_define_math| variable (be setting it to 0, works on the fly).

    For convenience, there are:
imap ~~		\tilde{}	
imap ~^		\hat{}		[^^ is used for ^{}]		

    The last two maps and the following maps work around |'timeout'| vim
    setting (behave like |'notimeout'| was set):

imap ==		&=
imap =~		\cong
imap ~~		\approx

imap ++		\sum		/ but not if before stand ^ or _ - this allows to type X_++ X^++/
imap o+		\oplus
imap O+		\bigoplus
imap o-		\ominus
imap o.		\odot
imap O.		\bigodot
imap o*		\otimes
imap O*		\bigotimes
imap t*		\times
imap s+		\cup		[    set +]		/set = set theoretic/
imap s-		\setminus	[    set -]
imap S+		\bigcup		[big set +]
imap s*		\cap		[    set *]
imap S*		\bigcap		[big set *]
imap c*		\prod		[    cat *]		/cat = categorical/
imap c+		\coprod		[    cat +]
imap l*		\wedge		[    lat *, meet]	/lat = lattice theoretic/ 
imap L*		\bigwedge	[big lat *]
imap l+		\vee		[    lat +, join]
imap L+		\bigvee		[big lat +]
imap <=		\leq
imap >=		\geq
imap ->		\rightarrow	or \draw[->] [inside tikzpicture environment]
imap <-		\leftarrow	or \draw[<-] [inside tikzpicture environment]
imap #>		\rangle
imap #<		\langle
imap _>		\Rightarrow
imap <_		\Leftarrow
imap |-		\vdash
imap -|		\dashv
imap t<		\triangleleft
imap t>		\triangleright
imap s<		\subseteq	[    set <]
imap s>		\supseteq	[    set >]

    If you want to write 'o*' you can wait until |'timeoutlen'| passes or
    write 'o *' (TeX in math mode doesn't see spaces).

 							*atp-imaps-diacritics*
							*g:atp_imap_define_diacritics*
DIACRITICS						*g:atp_imap_diacritics*

These imaps are defined in g:atp_imap_math variable.  They might be turned off
using |atp-:ToggleIMaps| commands or |g:atp_imap_define_diacritics| variable
(be setting it to 0, works on the fly).

							*g:atp_diacritics*
if |g:atp_diacritics| is set to 2 (the default) to get \'{a} you have to type
a`', i.e. the map acts on the character just before the cursor. See below
|g:atp_diacritics_letters|. Otherwise, if |g:atp_diacritics|=1 they act as
normal imaps, i.e. typing `' resolves to \'{} with cursor placed between the
brackets. If you set |g:atp_diacritics|=0 no diacritics imaps will be set.
Here is a list of all provided imaps to diacritics:
							*g:atp_diacritics_letters*
Inteligent diacritics works only after certain letters defined in the
dictionary |g:atp_diacritics_letters|, for example \'{} will work only after
one of the  letters in |g:atp_diacritics_letters|["'"]. The default value is:
>
    g:atp_diacritics_letters = {
	    \ "'"  : "aceginorsuyz",
	    \ "\"" : "aeiouy",
	    \ "`"  : "aeiouy",
	    \ "^"  : "aceghilosuwy",
	    \ "v"  : "acdehlnrstuz",
	    \ "b"  : "",
	    \ "d"  : "",
	    \ "H"  : "ou",
	    \ "~"  : "aeinouy",
	    \ "."  : "acegioz",
	    \ "c"  : "cegklnrst",
	    \ "t"  : "",
	    \ "2"  : "" }
<
Diacritics imaps: ~
>
    imap `'	\'{}
    imap `"	\"{}
    imap `^	\^{}
    imap `v	\v{}
    imap `b	\b{}
    imap `d	\d{}
    imap ``	\`{}
    imap `H	\H{}
    imap `~	\~{}
    imap `.	\.{}
    imap `c	\c{}
    imap `t	\t{}
<
You can also turn off diacritics imaps by setting |g:atp_imap_diacritics|=[] in
your |vimrc| or |atprc| file.

							*atp-:ToggleIMaps*
:ToggleIMaps
nmap, imap '<Tab> 
    This command toggles off/on impas defined in the vim lists
    g:atp_imap_math, g:atp_imap_math_misc and g:atp_imap_diacritics plus imaps
    to _{} and ^{}.

:ToggleSpace						*atp-:ToggleSpace*
	Turn on/off the cmap <Space> \_s\+.

LOG FILE MAPS						*atp-maps-log*
    This are available maps in the log file, when it was opened with
    |atp-:OpenLog| command >
	]e, [e 		- go to next/previous error message in log file 
	]w, [w		- go to next/previous warning message in log file 
	]c, [c		- go to next/previous citation warning message in log file 
	]r, [r		- go to next/previous reference warning message in log file 
	]i, [i		- go to next/previous info message in log file 
	]f, [f		- go to next/previous font info message in log file 
	]p, [p		- go to next/previous font package message in log file 
	]P, [P		- go to next/previous page in log file
	%		- searchpair for brackets: (:), [:], {:}, ... .
<	You can use |n| and |N| Vim normal commands to repeat previous search [count] times.


							*atp-vmap-WrapSelection*
WRAP SELECTION VMAPS					*atp-vmap-InteligentWrapSelection*
	These are the provided maps in visual mode: >
	    vmap <buffer> \rm	:<C-U>IWrap ['\\textrm{'],	['\\mathrm{']<CR>
	    vmap <buffer> \em	:<C-U>IWrap ['\\emph{'],	['\\mathit{']<CR>
	    vmap <buffer> \it	:<C-U>IWrap ['\\textit{'],	['\\mathit{']<CR>
	    vmap <buffer> \sf	:<C-U>IWrap ['\\textsf{'],	['\\mathsf{']<CR>
	    vmap <buffer> \tt	:<C-U>IWrap ['\\texttt{'], 	['\\mathtt{']<CR>
	    vmap <buffer> \bf	:<C-U>IWrap ['\\textbf{'],	['\\mathbf{']<CR>
	    vmap <buffer> \bb	:<C-U>IWrap ['\\textbf{'],	['\\mathbb{']<CR>
	    vmap <buffer> \tx	:<C-U>IWrap ['\\textrm{'],	['\\text{']<CR>
	    vmap <buffer> \sl	:<C-U>IWrap \\textsl{<CR>
	    vmap <buffer> \sc	:<C-U>Wrap \\textsc{<CR>
	    vmap <buffer> \up	:<C-U>Wrap \\textup{<CR>
	    vmap <buffer> \md	:<C-U>Wrap \\textmd{<CR>
	    vmap <buffer> \u	:<C-U>Wrap \\underline{<CR>
	    vmap <buffer> \o	:<C-U>Wrap \\overline{<CR>
	    vmap <buffer> \n	:<C-U>IWrap ['\\textnormal{'],['\\mathnormal{']<CR>
	    vmap <buffer> \cal	:<C-U>IWrap [''],['\\mathcal{']<CR>

	    vmap <LocalLeader>mb :Wrap \\mbox{ } begin<CR>
<   	Suggested maps: >
	    vmap <buffer> \tx	:<C-U>IWrap [''],['\\text{']<CR>
	    vmap <buffer> \in	:<C-U>IWrap [''],['\\intertext{']<CR>"
<	The leader '\' in above commands is configurable: the value of
	g:atp_vmap_text_font_leader is used (the default value is <LocalLeader>).

							*atp-nmap-WrapSelection*
							*atp-nmap-InteligentWrapSelection*
							*atp-omap-WrapSelection*
							*atp-omap-InteligentWrapSelection*
	The above maps are also valide in normal mode (operator mode). They require a motion
	afterwords, i.e. \rmw will wrap the following word inside \textrm{:}
	or \mathrm{:}.

	There is also: 
							*atp-vmap-\w*
	    						*atp-omap-\w*
>
	    omap <buffer> \w :set opfunc=ATP_LastWrap<CR>g@
	    vmap <buffer> \w :call atplib#various#RedoLastWrapSelection(["'<", "'>"])<CR>
< 	which repeats last wrappers used by |atp-:Wrap| or |atp-:IWrap|
	command or any other wrapping map.


	Another provided font wrapper: >
	    vmap <LocalLeader>f	:exe ':Wrap {\usefont{'.g:atp_font_encoding.'}{}{}{}\selectfont\  }'.(len(g:atp_font_encoding)+11).'<CR>'
<	Where the variable: 				*g:atp_font_encoding*
>
	    g:atp_font_encoding
<	stores the default encoding which is 'OT1', unless you use fontenc
	package, then the default for fontenc is used (the last defined in
	\usepackage[...]{fontenc} see the 'Latex2e font selection'
	/font user guide/ available on CTAN).

							*atp-vmap-bracket-wrappers*
	Other wrappers: >
	    vmap m			:Wrap \( \)<CR>
	    vmap M			:Wrap \[ \]<CR>
	    vmap <LocalLeader>(		:Wrap ( ) begin<CR>
	    vmap <LocalLeader>[		:Wrap [ ] begin<CR>
	    vmap <LocalLeader>{		:Wrap { } begin<CR>
	    vmap <LocalLeader>)		:Wrap ( ) end<CR>
	    vmap <LocalLeader>]		:Wrap [ ] end<CR>
	    vmap <LocalLeader>}		:Wrap { } end<CR>
	    vmap <LocalLeader>b(	:Wrap \left( \right) begin<CR>
	    vmap <LocalLeader>b[	:Wrap \left[ \right] begin<CR>
	    vmap <LocalLeader>b(	:Wrap \left( \right) begin<CR>
	    vmap <LocalLeader>b[	:Wrap \left[ \right] end<CR>
	    vmap <LocalLeader>b{	:Wrap \left{ \right} end<CR>
	    vmap <LocalLeader>b{	:Wrap \left{ \right} end<CR>
<
							*atp-nmap-bracket-wrappers*
	The above maps work also in normal mode, but they require a motion
	command afterwards, e.g. <LocalLeader>{w will wrap the following word
	inside {:}. Only m and M differs, in normal mode they are
	<LocalLeader>m (wrap with \(:\))and <LocalLeader>M (wrap with \[:\]).

	The maps to put the selected text into an environment: >
	    vmap <LocalLeader>A	:Wrap \begin{align} \end{align} 0 1<CR>
	    vmap <LocalLeader>C	:Wrap \begin{center} \end{center} 0 1<CR>
	    vmap <LocalLeader>E	:Wrap \begin{equation} \end{equation} 0 1<CR>
	    vmap <LocalLeader>L	:Wrap \begin{flushleft} \end{flushleft} 0 1<CR>
	    vmap <LocalLeader>R	:Wrap \begin{flushright} \end{flushright} 0 1<CR>
<
							*atp-vmap-WrapSelection-accents*
							*atp-vmap-InteligentWrapSelection-accents*
	Accent wrappers: are using the value of |g:atp_imap_over_leader| as
	a map leader, by default it is '`':
>
	    vmap <silent><buffer> `'	:<C-U>IWrap ["\\'{"],["\\acute{"]<CR>
	    vmap <silent><buffer> `"	:<C-U>Wrap \"{ } end<CR>
	    vmap <silent><buffer> `^	:<C-U>Wrap \^{ } end<CR>
	    vmap <silent><buffer> `v	:<C-U>IWrap ["\\v{"],["\\check{"]<CR>
	    vmap <silent><buffer> ``	:<C-U>IWrap ["\\`{], ["\\grave{"]<CR>
	    vmap <silent><buffer> `b	:<C-U>Wrap \b{ } end<CR>
	    vmap <silent><buffer> `d	:<C-U>Wrap \d{ } end<CR>
	    vmap <silent><buffer> `H	:<C-U>Wrap \H{ } end<CR>
	    vmap <silent><buffer> `~	:<C-U>Wrap \~{ } end<CR>
	    vmap <silent><buffer> `.	:<C-U>IWrap ["\\.{], ["\\dot{"]<CR>
	    vmap <silent><buffer> `c	:<C-U>Wrap \c{ } end<CR>
	    vmap <silent><buffer> `t	:<C-U>Wrap \t{ } end<CR>
<	The leader <LocalLeader> can be changes using the variable *g:atp_vmap_environment_leader* 
	(its default value is <LocalLeader>).
	Note: that the arguments for this command must be put in ':' or ":".
   	the highlighted text will put inside \textbf{ }. 
================================================================================
ABBREVIATIONS						*atp-abbreviations*

    The following abbreviations are defined:
	+- for \pm
	+| for \dagger
	++ for \ddager
	=<env_name>= for environments. 

    You can use |atp-completion| (<Tab>) for abbreviation names, see
    |atp-completion-abbreviations|.

    Locally defined environments are also supported (the one defined in
    |b:atp_LocalEnvironments|). They are made by the command
    |atp-:LocalCommands|, e.g if g:atp_local_completion == 2 then they are
    made on startup.

    If you need something different than abbreviation for
	\begin{theorem}
	     <Cursor placed here>
	\end{theorem}
    for example:
	\begin{corollary}<Cursor placed here>
	\end{corollary}
    You can set the variable g:atp_abbreviation_{environment_name}. It is list
    with two elements. First element is used after \begin{...} and the second
    after \end{...}. For the above examples:
	let g:atp_abbreviation_theorem		= [ '<CR>', '<ESC>O' ]
	let g:atp_abbreviation_corollary	= [ '<CR>', '<ESC><UP>A' ]
    The first one is the default so you do not need to set it. In the second
    example the abbreviation command will look like: >
	abbreviate =corollary= \begin{corollary}<CR>\end{corollary}<ESC><UP>A
<   This will only work for b:atp_LocalEnvironments; LaTeX and AMS
    environments are set accordingly.
    Environment name abbreviations are defined only if there were not defined.
    So you can override the settings using |atprc| file (or |vimrc| file).

    Furthermore, you can change the "=":
    							*g:atp_iabbrev_leader*
    let g:atp_iabbrev_leader = "="
	It is used  in insert mode abbreviations like: =theorem=. 

    							*g:atp_no_local_abbreviations*
    Use |g:atp_no_local_abbreviations| if you don't want to have abbreviations
    to locally defined environments (this takes time if your vim was compiled
    without |+python| feature, as it runs |atp-:LocalCommands| command - which
    is slow in this case).

================================================================================
DEBUGGING						*atp-errors*
    This section describes some limitation of ATP (as you see, this section is
    not written, but the aim is to make it disappear anyway ;).

    There are many debug variables with names g:atp_debug{fname} where {fname} is
    a shortname of the function for which it will turn on the debug info. These
    variables are documented in ftplugin/ATP_files/options.vim file.

							*atp-errors-bibsearch*
    A possible error which may occur using the :BibSearch commands has a simple
    cause: we count number of brackets '()', '{}' and '"' (but nor '\"') to see
    where the bib entry ends and where to join lines. The message error is echoed
    when more than 30 lines where processed and the matching bracket was not found
    (or the number of '"' is odd). Look at your bib file at the specified
    position.  Syntax highlighting for bib files can help you finding where such
    an error is located. (After reading the bib file comment lines and lines which
    begin with @string are removed, so that the brackets in comment lines do not
    count.)

================================================================================
EDITING TOOLS							*atp-editing*

							*atp-visual*
	visual mode: i), i(, a), a(, i], i[, a], a[, i}, i{, a}, a{,
	ie, iE, ae, im, am, ip, ap, iS, aS, <LocalLeader>sc normal
	and mode: <LocalLeader>sc. 

	They select the current environment in two ways: >
	    i 		- inner
	    a 		- outer
	    e 		- environment 
	    p		- paragraph	  
	    m		- math zones: \(:\), $:$, \[:\], $$:$$, 
			  or math environment \begin:\end.ard
			  search is set by ATP
	    (,),{,},[,]	- brackets
	    s	- syntax
<							*atp-vi)* *atp-vi(*
							*atp-vi]* *atp-vi[*
	i), i(, i], i[ -- select between (:) and [:] without the bracket
	sizes, i.e. '\left(XXX\right)' i( and i) will select 'XXX'. These maps
	will not select between \(:\), and \[:\] (for these use |atp-im|)
							*atp-vi}* *atp-vi{*
	i}, i{ -- select between {:} and \{:\} (omitting sizes as above)
 							*atp-va)* *atp-va(*
							*atp-va]* *atp-va[*
	a), a(, a], a[ -- select between (:) and [:] together with the
	brackets and the bracket sizes, i.e. a) and a( over '\left(XXX\right)'
	will select whole sequence. These map will not select \(:\) and \[:\]
	(use |atp-am| instead)
							*atp-va}* *atp-va{*
	a}, a{ -- select between {:}, \{:\} together with the sizes.

							*atp-omap-i)* *atp-omap-i(*
							*atp-omap-i]* *atp-omap-i[*
							*atp-omap-i}* *atp-omap-i{*
 							*atp-omap-a)* *atp-omap-a(*
							*atp-omap-a]* *atp-omap-a[*
							*atp-omap-a}* *atp-omap-a{*
	The corresponding operator maps are defined. For example you can use
	ci( to change the inner part of \left(...\right), etc.

							*atp-vie* *atp-viE* *atp-vae*
	ie, iE, ae select environment: from the nearest \begin (top) to the nearest \end (bottom).	

		'viE' selects a bit more than 'vie' but less than 'vae', it
		selects a bracket pair before the beginning of the inner part
		of an environment, so it can be environment name or an option
		just after. 	

							*atp-vim* *atp-vam*
	im, am	selects mathematics.
							*atp-vip* *atp-vap*
	ip, ap  selects paragraph. 
		In inner mode (ip): from the nearest >
			\begin, \end, \par, \newline, ^\s*% (comment) or empty line (top) 
<		to the nearest >
			\begin, \end, \par, \newline,  ^\s*% (comment)or empty line (bottom).
<		in outer mode (ap): from the nearest >
			\par or empty line (top) 
<		to the nearest >
			\par or empty line (bottom).
<						
	ip over a commented line will match all the comment like =c

							*atp-omap-im* *atp-omap-am*
							*atp-omap-ip* *atp-omap-ap*
	The correspondin operator maps are defined. For example you can use
	xim to delete the inner part of math mode \(:\), etc.

							*atp-viS* *atp-vaS*
	iS, aS	selects using syntax stack (see |synstack()|), inner is the
		top element in the syntax stack (the highlighted area will be
		small) and outer uses the most bottom element in the syntax
		stack (the resulting are will be wide). Some syntax groups are
		filtered out (like 'texDocZone') which not always are
		synchronised.
							*atp-select-comments*
							*g:atp_MapSelectComment*
							*atp-=c*
	=c	
		select comment lines which begin with '^\s*%'. If not in
		comment line, end visual mode. You can change this map with
		variables g:atp_MapSelectComment (this can be only changed in
		atprc or vimrc file, you need restart Vim, or use
		|atp-:ReloadATP|) .
							*atp-omap-=c*
		The corresponding operator map is defined, e.g. you can use
		d=c to delete the comment.


							*atp-gw*	
nmap gw
	Quite useful normal map: m`vipgq``. It is mapped to gw (in normal
	mode).

							*atp-g<*
							*atp-g>*	
nmaps: g>, g<, 2g>, ..., 6g>  
	A normal map to m`vipg>`` (or m`vip2g>``).
								
							*atp-r*
nmap r{char}
	Over any charackter which is not a bracket: (:), [:], {:} it acts as
	|r| command. Over a bracket which has a closing bracket and if {char}
	is another bracket it replaces both opening and closing bracket. When
	replacing brackets it will not remember the changing bracket for the
	|.| command, so you cannot use |.| to change more brackets, but if
	|atp-r| was used for changing text (non-brackets, or not-closed/opened
	brackets) then the action can be repeated with |.|.


================================================================================
REQUIREMENTS						*atp-requirements*

This plugin requires Vim version 7.3.  Several tools uses syntax, so even if
you do not like colours on the screen you should set "syntax on". For example,
the recognition of math mode used by |atp-completion|, and |atp-:TexAlign|
command (but also some other things, and some maps!).

							*atp-requirements-python*
ATP uses python 2.7 (also works with python 3). You need psutil library which
you can get from here:
    http://code.google.com/p/psutil/
Other libraries are standard ones so they should be available. If you have
a problem you can try to set g:atp_debugPythonCompiler=1 and then look at the
file PythonCompiler.log under |g:atp_TempDir| it will contain python errors.

It is nice to have 'texdoc' program. This plugin maps <F1> to a function which
calls it. This allows to speed up searches for documentation. Also the option
'keywordprg' has the value "texdoc -m", thus pressing 'K' (see |K|) over a tex
package should open you the package documentation. The same applies to this
help file.

Another good programs are: texloganalyzer (which is now not used by ATP) and pdffonts
There is a map to use pdffonts, see: |pdffonts|.

The command |atp-:WordCount| is using detex program. It is included in TexLive
tex distribution.

================================================================================
NOTES ON VIEWERS                          		*atp-Viewers*

See the section |atp-Viewers_Options| how to set options for viewer programs.

 							*atp-Viewers-Xpdf*
Xpdf ~
	It is supported. It is configured in the way that when your tex file
	have errors, Xpdf viewer will not reload your file, which I found
	useful. Xpdf supports forward searching (vim->Xpdf) with command:
	|atp-:SyncTex| >
		:SyncTex
		map <LocalLeader>f
		map <S-LeftMouse>
<	Read also |atp-:SyncTex_Xpdf-hack| and see |atp-:SetXpdf| command
	description.  You can set your own options of Xpdf using
	|b:atp_xpdfOptions| (or g:atp_xpdfOptions), for example:
>
	    let b:atp_xpdfOptions=['-bg', 'NavajoWhite4', '-fg', 'black', '-mattecolor', 'burylwood']
<
	will make Xpdf view different. This is helpful when you edit to
	files, and do not want to mix them. Another nice example:
>
	    let b:atp_xpdfOptions="-bg Grey30 -mattecolor SlateBlue2 -papercolor White"
<

	You can set forward searching for Xpdf (from version 3.03, already
	available here: http://foolabs.com/xpdf/download.html):

Xpdf: inverse search ~
							(see also |atp_inverse_search|)
	Add this line to your $HOME/.xpdfrc file: >
	    bind shift-mousePress1 any 'run(python $HOME/.vim/ftplugin/ATP_files/atp_RevSearch.py --synctex  "%f" %i %j %k)'
<	Note: %i, %j, %k should not be quoted.
	Pressing <Shift>+<Left_Mouse> will do forward search, i.e. it will set
	vim according to mouse cursor position over Xpdf. See man page of xpdf
	how to bind other keys.

	Note: to use this xpdf have to be opened giving full path to the file.
	This is important when you open a file from a terminal. Otherwise
	atp_RevSearch.py as invoked above by the run() command will look for
	the tex file in the directory: '$HOME/.vim/ftplugin/ATP_files'.
	Furthermore, it will make new file there which ATP will try to process.
	A workaround this should be to place atp_RevSearch somewhere in your
	path and make in executable and change the run() command to
	'run(atp_RevSearch.py --synctex %f %i %j %k)'. This is not tested solution.

	You can debug Xpdf if something doesn't work: open the file from terminal
	with 'xpdf -cmd' see the man page of Xpdf.

Evince ~
	Works fine.
							*atp-Viewers-Okular*
Okular ~
	Works fine. It supports both forward (Vim->Okular) and inverse
	(Okular->Vim) searches. Okular supports forward searching (vim->Okular)
	with command: |atp-:SyncTex| >
		:SyncTex
		map <LocalLeader>f
		map <S-LeftMouse>
<
Okular: inverse search ~
	Here is how to configure inverse searching (Okular->Vim) with
	|atp_RevSearch.py| python script shifted with ATP: 

	open Okular and go to >
		settings>Configure Okular>Editor
<	and set >
		Editor		Custom Text Editor
		Command		python $HOME/.vim/ftplugin/ATP_files/atp_RevSearch.py '%f' '%l'
<	NOTE: You must substitute $HOME directory to its value!!! It will not
	work other way. You can also copy the script somewhere inside your
	$PATH but then when this script will change you have to keep in mind
	to copy it again. 

	If it is not working for you, please report it, you can also
	use: >
	    gvim --remote-wait +%l "+normal %c|" %f
<
							*atp-:SyncTex_with_Okular*
	NOTE: :SyncTex command uses "--unique" switch for okular. However,
	when you do not set |b:atp_okularOptions| to ["--unique"] as well, then
	using :SyncTex will open new instance of Okular regardless if it was
	opened or not. You can use "--unique" as an Okular option (in
	g:atp_okularOptins or b:atp_okularOptions), but the if you open many
	files tex, all will use only one instance of Okular. This is
	a limitation of using Okular. Xpdf has a server option which allows
	for vim->Xpdf communication to the right Xpdf instance.  

	Then you can use <Shift>+<Left_Mouse> in Okular to synchronize the Vim
	(gVim) with pdf. 

							*atp-Viewers-Skim*
							*atp-Viewers-Open*
Skim ~
Open ~
	Forward searching (vim -> open): ~
        To enable forward searching you need to:
							*g:atp_DisplaylinePath*
	ATP is using the following path to displayline:
            /Applications/Skim.app/Contents/SharedSupport/displayline
	it is defined in the variable |g:atp_DisplaylinePath|.

	To set reverse searching for Skim (Skim -> Vim):
	   Enable Preferences > Sync > Check for file changes
	   Preset   = Custom
	   Command  = /usr/local/bin/mvim
	   Argument = --remote-silent +":%line" "%file"
	    	    

Kpdf ~
	Works fine (moves page a little bit when updates a file).

EpdfView ~
	This viewer does not support automatic reloads when the file changes
	(but it seems that the work is in progress). You have to issue CTRL-R
	yourself when the file is changed.

AcroRead ~
	As with epdfview (with the difference that it supports automatic
	updates, but it do not works somehow). There is a way to configure
	forward searching (Vim->AcroRead)! but it is not supported yet, if you
	really want it, write to me.
							*atp-Viewers-Xdvi*
Xdvi ~
	Works fine. The file will be updated after a click (or use the xdvi
	options '-watchfile 1' see man xdvi for explanations). You can set
	forward/reverse searching by the command |SetXdvi| then use
	|atp-:SyncTex| for forward searching (Vim->Xdvi). To get reverse
	searching Xdvi must be opened by ATP (:View, or any other
	command)

	If you want to use Vim you have to run it with the command: >
 		vim --servername xdvi <file>
<	You can pick any server name.
	
	ATP supports forward (Vim->Xdvi) and inverse (Xdvi->Vim) searching for
	Xdvi. The forward search is set by ATP (see |atp:SyncTex|), the
	inverse search is set by: >
	    let b:atp_TexCompiler	= "latex"
	    let b:atp_TexOptions	= ["-src-specials"]
	    let b:atp_Viewer		= "xdvi" 
	    let b:atp_xdviOptions	= ["-editor", "'gvim --remote-wait +%l %f'", "-watchfile", "1"]
<	They are not set by default, however there is simple command to set
	them at once |atp-:SetXdvi|.	
	This are excellent sources of information on this:
	    http://xdvi.sourceforge.net/inverse-search.html
	    http://Vim.wikia.com/wiki/Vim_can_interact_with_xdvi
	Note the watchfile switch for xdvi: with it xdvi will reload the file,
	if needed, every second.

Zathura	~
	Perfectly works (but there is no reverse/inverse searching).

Mupdf ~
	It is the fastest pdf viewer program ever made, why? because it
	renders only one page :). But it can be nicely set with ATP: via
	autocommands and |atp-:SyncTex| you can load a page where the cursor is
	located (for example with autocommand event |CursorHold|). This might be
	nice on a big enough monitor on which you can see both vim and mupdf
	on one screen.

================================================================================
INVERSE SEARCHING					*atp_inverse_search*

							*atp_RevSearch.py*
	ATP comes with a python script which can do inverse searching. It is
	based on synctex and a vim function |atplib#FindAndOpen()|. The last
	function searches which running vim/gvim instance holds the {file},
	and updates the cursor location. The syntax is as follows:

	    atp_RevSearch.py [--gvim] {file} {line} [column]
	    atp_RevSearch.py [--gvim] --synctex {file} {page} {x-coord} {y-coord}

	First syntax will work for viewers which calls synctex themselves
	(like Okular) and has escapes for {line} (and [column]).  The second
	syntax is for viewers which have only escapes characters for {page}
	number and the coordinates {x-coord} and {y-coord} (for example Xpdf).

	Note: {x-coord} and {y-coord} counts from top left corner in big
	points (72dpi), for example Xpdf (ver. 3.03) gives escapes for x,
	y coordinates counting from bottom left corner)

	Preferably you should call this command with >
	    python PATH/atp_RevSearch.py  {args}
<	Then when you update ATP you will not miss updates of |atp_RevSearch.py|. 
	Another good solution is to link |atp_RevSearch.py| somewhere in the
	$PATH and make it executable. If you just copy it you might miss when
	it will be updated. If you set the command as above (with python
	before the path to atp_RevSearch.py) you do not need to make
	atp_RevSearch.py executable.  Note, that otherwise whenever you update
	ATP you will have to make the script executable!

	By default, the script is using gvim. If you prefer to use vim add
	[--vim] switch: >
	    python PATH/atp_RevSearch --gvim --synctex {file} {page} {x-coord} {y-coord}
<
	Note: |atp_RevSearch.py| doesn't like when you suspend an instance of
	vim (any).

	|atp_RevSearch.py| write to a debug file /tmp/atp_RevSearch.py.

	Note: if inverse searching stopped working for you, try to recompile
	the document.

	Finally, |atp_RevSearch.py| will forward error messages (or error code
	if error message was not found) back to vim. This is only possible if
	|atp_RevSearch.py| found the correct vim server.

							*atplib#FindAndOpen()*	
	The function atplib#FindAndOpen() asks each running gvim server if is
	is "hosting" source of the file %f. Then it uses this server to set
	the line (but it doesn't check if the cursor is in the right window!).

	Note: if you like command line Vim (which has its own beauty
	- actually I'm just typing in it :) you need to set up Vim server
	  option on startup: >
 		vim --servername VIM <file>

<	|atplib#FindAndOpen()| will find a correct tabpage and window if
	necessary and focus vim in the right one.
	Limitations: ~
	The project files which are split into many input files are not yet
	supported.
	

================================================================================
TIPS                               			*atp-tips*

If you have any nice tip on editing (La)TeX with Vim or ATP :) you can share it
here (my email you'll find on top of the help file), or put them on the script
web page. 


nmap gS :%s/<c-r>=expand("<cword>")<cr>/
				Pull word under the cursor to substitute
				command. 

:g/^[^%]*\\usepackge/#		List loaded packages with line numbers
				If you want to keepjumps and do not move the
				cursor you can use this:
:g/^[^%]*\\usepackage/keepjumps #|normal ''

y/\\begin{document}/		When standing on 1st line - copy the preamble
				(possibly to a register)
:g/^\s*%/d			Delete comment lines 				

:g/\(^\s*\n\)\{2,}/d		Compress empty lines 
					/ when there are more than two empty
					lines it leaves just one /  
				or even better:
:g/^\s*$/,/\S/-j
				or even better:
:v/./,/./-j
				but this will compress only empty lines,
				see http://vim.wikia.com/wiki/Power_of_g for
				explanation.

:g/\\begin{table}/+;/\\end{table}/-s/\(\\\\\s*\)\@<!\n/
				Joint lines inside table environment which
				doesn't end with \\, i.e. from >
				    \begin{table}
					    a&b
					    c&d\\
					    A&B&C
					    &D\\
				    \end{table}
<				it will make >
				    \begin{table}
					    a&b&c&d\\
					    A&B&C&D\\
				    \end{table}
<				(modulo white spaces which might appear)

vipgq				Format inner paragraph. Or even better:
m`vipgq``			This is so nice that I added a map: >
				    nmap gq	m`vipgq``		
<
m`vip>``			
m`vip<``			Indent inner paragraph, they are mapped to: >
				    nmap g>	m`vip>``
				    nmap g<	m`vip<``
<				There are also defined maps: 2g>, 3g> , 4g>
				up to 6g>.

:TeXdoc amsCTRL-d		Show tex documentation which matches ams (the
				completion for TeXdoc command finds matches in
				alias files of texdoc :!texdoc -f).

\ref{thm:<Tab>			It will list all cross references to theorems
\ref{^thm:<S-Tab>		(if you use the prefix thm: for theorems).
				
				If you want to change the name of a command,
				you can try:
augroup DelCommands
    au VimEnter *tex delcommand SetXdvi
    au VimEnter *tex delcommand SetXpdf
augroup END
command! -buffer	Xdvi	:call SetXdvi()
command! -buffer	Xpdf	:call SetXpdf()

				However, not all functions are defined without
				<SID> (you can always try to reach me).

:'<,'>WrapSelection @q		Wrap a visual area with wrapper from the
				register q and with the default '}' end
				wrapper.
:'<,'>WrapSelection @q,@w	As above but with the end wrapper from
				register w. 

:map ]=		]sz=		Goto the first spelling error and list 
:map [=		[sz=		suggestions. Another version is to use
				]S and [S instead of ]s and [s.
				
imap <C-B>	<C-o>b<C-o>de	Delete word before the cursor
		<C-o>vbx	(this an alternative using visual mode).

The vim motions w and b in TeX/LaTeX might behave a bitt better if they treat
\ as a place where word starts/ends. If you add \ to 'iskeyword' option, then
this will not work. As a workaround you can use the following functions:

fun! Wmotion(count, mode)
    let i=1
    let beg_pos = getpos(".")
    while i <= a:count
	if getline(line("."))[col(".")-1:col(".")] =~? '^\\\w'
	    normal! w
	endif
	normal! w
	if getline(line("."))[col(".")-2] == "\\"
	    normal! h
	endif
	let i+=1
    endwhile
    if a:mode ==? 'v'
	if a:mode ==# 'v'
	    normal! v
	else
	    normal! V
	endif
	call cursor(beg_pos[1:2])
	normal! o
    endif
endfun
nmap <buffer> <silent> w :<C-U>call Wmotion(v:count1, 'n')<CR>
vmap <buffer> <silent> w :<C-U>call Wmotion(v:count1, 'v')<CR>
omap <buffer> <silent> w :<C-U>call Wmotion(v:count1, 'o')<CR>

fun! Bmotion(count, mode)
    let i=1
    let beg_pos = getpos(".")
    while i <= a:count
	normal! b
	if getline(line("."))[col(".")-2] == "\\"
	    normal! h
	endif
	let i+=1
    endwhile
    if a:mode ==? 'v'
	if a:mode ==# 'v'
	    normal! v
	else
	    normal! V
	endif
	call cursor(beg_pos[1:2])
	normal! o
    endif
endfun
map <buffer> <silent> b :<C-U>call Bmotion(v:count1, 'n')<CR>
vmap <buffer> <silent> b :<C-U>call Bmotion(v:count1, 'v')<CR>
omap <buffer> <silent> b :<C-U>call Bmotion(v:count1, 'o')<CR>

fun! Emotion(count, mode)
    let i=1
    let beg_pos = getpos(".")
    while i <= a:count
	normal! e
	if getline(line("."))[col(".")-1] =~ "\\"
	    normal! e
	endif
	let i+=1
    endwhile
    if a:mode ==# 'o'
	normal! l
    elseif a:mode ==? 'v'
	if a:mode ==# 'v'
	    normal! v
	else
	    normal! V
	endif
	call cursor(beg_pos[1:2])
	normal! o
    endif
endfun
map <buffer> <silent> e :<C-U>call Emotion(v:count1, 'n')<CR>
vmap <buffer> <silent> e :<C-U>call Emotion(v:count1, 'v')<CR>
omap <buffer> <silent> e :<C-U>call Emotion(v:count1, 'o')<CR>

fun! OuterWord()
    call search('\<\|\\', 'cb')
    if getline(line("."))[col(".")-2] == "\\"
	normal! h
    endif
    normal ve
endfun
vmap <buffer> <silent> aw <Esc>:call OuterWord()<CR>

================================================================================
COLOUR HIGHLIGHTING AND SYNTAX GROUPS			*atp-highlight*

When the cursor is positioned on \begin{envname} or \end{envname} both
corresponding \begin:\end get highlighted with syntax group MatchParen. 
To disable it type this in ex mode or put it in your atprc file: >
	augroup LatexBox_HighlightPairs 
	     au!
	augroup END
<

There is a colour scheme included: coots-beauty-256. You need 256 colours to use
it (in the terminal). 

These are the highlights groups defined for various files and the default
links:

1) ToC file >
	highlight atp_FileName		Title
	highlight atp_LineNr		LineNr
	highlight atp_Number		Number
	highlight atp_Chapter		Label
	highlight atp_Section		Label
	highlight atp_SubSection	Label
	highlight atp_Abstract		Label
<		*this group highlights abstract and all the unnumbered chapters
		 and the bibliography.

    The chapter group highlights or chapters, or sections, or parts, depending
    what is your top level section in your latex document. This applies,
    accordingly, to other groups.

2) Labels file >
	highlight atp_label_FileName	Title
	highlight atp_label_LineNr	LineNr
	highlight atp_label_Name 	Label
	highlight atp_label_Counter 	Keyword
<
3) BibSearch file
    this is very much the same as the standard syntax for bib files. Groups
    are named bibsearch<NAME> instead of bib<NAME>. There is one more group
    added:
>
	highlight bibsearchInfo
<
    which highlights the line number of the bib entry in the bib file.  All
    bibsearch groups are by default linked to the bib groups.

    Yet, there is no default highlighting, try coots-beauty-256 colour scheme.
    If you like it, I'm glad, if you have a nice (non standard) colour scheme,
    I'm happy to get it, if you like to share it.

4) Status line:
    The notification message that your compiler is running can be highlighted.
    For this set the variables: >
    	g:atp_notification_{g:colors_name}_gui
    	g:atp_notification_{g:colors_name}_guifg
    	g:atp_notification_{g:colors_name}_guibg
<   Their values will be passed to gui guifg and guibg values of the highlight
    command. The g:colors_name variable is set by colour scheme. Usually it is
    just the colour scheme name but there might be a difference, for example:
    the provided colour scheme file name is 'coots-beauty-256' but the variable
    is set to 'coots_beauty_256'. Example: >
    	let g:atp_notification_coots_beauty_256_gui="DeepPink4"
<   will set the foreground colour of 'pdfLaTeX' message to DeepPink4.

							*atp-highlight-notification*
    The status message 'LaTeX' ( if you use latex or 'pdfLaTeX' when you use
    pdflatex, and so on) can be highlighted. There are several variables to
    set this: >
		g:atp_notification_{g:colors_name}_gui
		g:atp_notification_{g:colors_name}_guifg
		g:atp_notification_{g:colors_name}_guibg

		g:atp_notification_{g:colors_name}_cterm
		g:atp_notification_{g:colors_name}_ctermfg
		g:atp_notification_{g:colors_name}_ctermbg
<   where g:colors_name is the name of the colour scheme, for example the
    supplied colour scheme with atp 'runtimepath/colors/coots-beauty-256' has
    name 'coots_beauty_256' so the first variable should be >
		g:atp_highlight_coots_beauty_256_gui
<   value of these variables are used to set highlight for the group UserN
    where N is the value of g:atp_statusNotifHi. Its value should be
    0,1,...,9. Where 0 means no highlight for status notification (which is
    the default). If it is set to positive value then the default values of
    these variables should give the same colour as the status line has.

    							*g:atp_StatusLine*
    The variable g:atp_StatusLine is stores the value of Vim option
    'statusline'; actually 'statusline' option is set by: >
		set statusline=%!g:atp_StatusLine
<

================================================================================
ATP DEVELOPMENT						*atp-development*

g:atp_atpdev = 0					*g:atp_atpdev*
If you set this to 1 the following command will be available.
:DebugPrint 						*atp-:DebugPrint*
    if you want to develop/debug ATP set g:atp_atpdev to 1 run
    |atp-:ReloadATP| and this command will allow to print (cat) debug
    files under |g:atp_TempDir|.

Debug information is accessible for almost every function, but it is turned
off by default. The variable names for that are g:atp_depub{FunctionName},
where {FunctionName} is or name of the function or an abbreviation. See
section in ftplugin/ATP_files/options.vim script.

================================================================================
FINAL REMARKS                               		*atp-remarks*
	
	To see some messages that are issued you can use the |:mes| command.

	If you find this plugin useful and have some comments you are
	cordially invited to write to the author: <mszamot [AT] gmail [dot]
	com>, add some "karma" points on vim script page, make
	a recommendation or write a review on SourceForge: |atp-sourceforge|.

	Best, and hopefully you will find this useful :) 
	Marcin Szamotulski
	
	
================================================================================
COPY RIGHTS						*atp-copy-rights*


    Copyright (C) 2010 Marcin Szamotulski Permission is hereby granted to use
    and distribute this code, with or without modifications, provided that
    this copyright notice is copied with it. 

    Automatic Tex Plugin for Vim is free software: you can redistribute it
    and/or modify it under the terms of the GNU General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.
 
    Automatic Tex Plugin for Vim is distributed in the hope that it will be
    useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
    Public License for more details.
 
    You should have received a copy of the GNU General Public License along
    with Automatic Tex Plugin for Vim.  If not, see <http://www.gnu.org/licenses/>.

    This licence applies to all files shipped with Automatic Tex Plugin,
    excluding the following two dictionary files: >
	"ftplugin/ATP_files/dictionaries/dictionary",
	"ftplugin/ATP_files/dictionaries/SIunits" 
<   where taken from latex-suite Vim plugin and are under Vim charity

 vim:tw=78:ts=8:ft=help:norl:
doc/bibtex_atp.txt	[[[1
62
*bibtex_atp.txt* BibTeX filetype plugin (ATP)		Last change: 7 November 2010

			HELP file for BIBTEX file type plugin of 
			    Automatic TeX Plugin
				by Marcin Szamotulski
			    mszamot [AT] gmail [DOT] com
			----------------------------------------

-----------------------------------------------------------------------------
If you found this plugin useful or you have any kind of problems with running
it or some ideas to share, you are cordially invited to write to me:
mszamot@gmail.com. Voting at Vim site is also welcome ;) .
-----------------------------------------------------------------------------

			   *atp-bibtex*

-----------------------------------------------------------------------------
MOTIONS						*atp-bibtex-motions*
    ]], }	go to next field (and use zz to redraw the screen)
    [[, {	go to previous field (and use zz to redraw the screen)
    ][		go to end of the current bib field
    []		go to end of the previous bib field
    <C-j>	(both map and imap) go to next bib entry (after { or ( or " or ').
    <C-k>	(both map and imap) go to previous bib entry (after { or ( or " or ').

-----------------------------------------------------------------------------
COMMANDS					*atp-bibtex-:AMSRef*
:AMSRef {bib_data}  
    Command to get bib data from AMSRef:
		http://www.ams.org/mathscinet-mref 
    The bib data will be appended to the currently edited bibliography just
    before the next bib field. You will be asked for the bib key, the default
    choice is to use the AMS bib key.  The obtained bibliographic reference is
    copied to the register g:atp_bibrefRegister (the default is "0" so you can
    paste it using vim command 'p') and also is stored in the variable
    g:atp_bibref.
	
-----------------------------------------------------------------------------
MAPS						*atp-bibtex-maps*
    There is a new ftplugin for bib files. It only defines a small set of
    useful maps and the AMSRef command. The defined maps are listead below: 
		MAP KEY			FIELD TYPE: 
		<LocalLeader>a		article
		<LocalLeader>b (or bo)	book
		<LocalLeader>bl		booklet
		<LocalLeader>c		conference
		<LocalLeader>ib		inbook
		<LocalLeader>ic		incollection
		<LocalLeader>ip		inproceedings
		<LocalLeader>ma		manual
		<LocalLeader>mt		mastersthesis
		<LocalLeader>mi		misc
		<LocalLeader>phd	phdthesis
		<LocalLeader>pr		proceedings
		<LocalLeader>tr		techreport
		<LocalLeader>un		unpublished

    With <F1> you will get help on bibtex: 'BibTeXing' by Oren Patashnik.

-----------------------------------------------------------------------------
COPY RIGHTS					*atp-bibtex-copy-rights*
	See |atp-copy-rights|.
doc/latexhelp.txt	[[[1
2447
*latexhelp.txt*    For Vim version 6.0.  Last change: 2001 Dec 20


				LATEX HELP 1.6  
		   translated (with minor changes) for vim
			     by Mikolaj Machowski

This file documents LaTeX2e, a document preparation system. LaTeX2e is a
macro package for TeX.

  This is edition 1.6 of the LaTeX2e documentation, and is for the Texinfo
that is distributed as part of Version 19 of GNU Emacs. It uses version
2.134 or later of the texinfo.tex input file.

  This is translated from LATEX.HLP v1.0a in the VMS Help Library.  The
pre-translation version was written by George D. Greenwade of Sam Houston
State University.

  The LaTeX 2.09 version was written by Stephen Gilmore <stg@dcs.ed.ac.uk>.

  The LaTeX2e version was adapted from this by Torsten Martinsen
<bullestock@dk-online.dk>.

  Version for vim of this manual was written by Mikolaj Machowski
<mikmach@wp.pl>

  Copyright 1988,1994 Free Software Foundation, Inc.  Copyright 1994-1996
Torsten Martinsen. Copyright for `translation' for vim Mikolaj Machowski 2001.

  Permission is granted to make and distribute verbatim copies of this manual
provided the copyright notice and this permission notice are preserved on
all copies.

  Permission is granted to copy and distribute modified versions of this
manual under the conditions for verbatim copying, provided that the entire
resulting derived work is distributed under the terms of a permission
notice identical to this one.

  Permission is granted to copy and distribute translations of this manual
into another language, under the above conditions for modified versions,
except that the sections entitled "Distribution" and "General Public
License" may be included in a translation approved by the author instead of
in the original English.

==============================================================================
*LaTeX* *latex*

The LaTeX command typesets a file of text using the TeX program and the LaTeX
Macro package for TeX. To be more specific, it processes an input file
containing the text of a document with interspersed commands that describe how
the text should be formatted.

1.  Commands					|latex-commands|
2.  Counters					|latex-counters|
3.  Cross References				|latex-references|
4.  Definitions					|latex-definitions|
5.  Document Classes				|latex-classes|
6.  Layout					|latex-layout|
7.  Environments				|latex-environments|
8.  Footnotes					|latex-footnotes|
9.  Lengths					|latex-lengths|
10. Letters					|latex-letters|
11. Line & Page Breaking			|latex-breaking|
12. Making Paragraphs				|latex-paragraphs|
13. Margin Notes				|latex-margin-notes|
14. Math Formulae				|latex-math|
15. Modes					|latex-modes|
16. Page Styles					|latex-page-styles|
17. Sectioning					|latex-sectioning|
18. Spaces & Boxes				|latex-spaces-boxes|
19. Special Characters				|latex-special-char|
20. Splitting the Input				|latex-inputting|
21. Starting & Ending				|latex-start-end|
22. Table of Contents				|latex-toc|
23. Terminal Input/Output			|latex-terminal|
24. Typefaces					|latex-typefaces|
25. Parameters					|latex-parameters|

==============================================================================
1. Commands					*latex-commands*

A LaTeX command begins with the command name, which consists of a \ followed
by either
	(a) a string of letters or
	(b) a single non-letter.

Arguments contained in square brackets, [], are optional while arguments
contained in braces, {}, are required.

NOTE: LaTeX is case sensitive. Enter all commands in lower case unless
explicitly directed to do otherwise.

==============================================================================
2. Counters					*latex-counters*

|\addtocounter|		Add a quantity to a counter
|\alph|			Print value of a counter using letters
|\arabic|		Print value of a counter using numerals
|\fnsymbol|		Print value of a counter using symbols
|\newcounter|		Define a new counter
|\refstepcounter|	Add to counter, resetting subsidiary counters
|\roman|		Print value of a counter using roman numerals
|\setcounter|		Set the value of a counter
|\stepcounter|		Add to counter, resetting subsidiary counters
|\usecounter|		Use a specified counter in a list environment
|\value|		Use the value of a counter in an expression

Everything LaTeX numbers for you has a counter associated with it. The name of
the counter is the same as the name of the environment or command that
produces the number, except with no |\\|. (|lc-enumi| - |lc-enumiv| are used
for the nested |\enumerate| environment.) Below is a list of the counters
used in LaTeX's standard document classes to control numbering.

 |part|          |paragraph|     |figure|      |enumi|    |itemi|
 |chapter|       |subparagraph|  |table|       |enumii|   |itemii|
 |section|       |page|          |footnote|    |enumiii|  |itemiii|
 |subsection|    |equation|      |mpfootnote|  |enumiv|   |itemiv|
 |subsubsection|


\addtocounter{counter}{value}			*\addtocounter*
		Increments the {counter} by the amount specified by the
		{value} argument. The {value} argument can be negative.

\alph{counter}					*\alph* *\Alph*
\Alph{counter}
		This command causes the value of the counter to be printed in
		alphabetic characters. |\alph| command uses lower case
		alphabetic alphabetic characters, i.e., a, b, c... while the
		|\Alph| command uses upper case alphabetic characters, i.e.,
		A, B, C....

\arabic{counter} 				*\arabic*
		Causes the value of the {counter} to be printed in Arabic
		numbers, i.e., 3.

\fnsymbol{counter} 				*\fnsymbol*
		Causes the value of the {counter} to be printed in a specific
		sequence of nine symbols that can be used for numbering
		footnotes.
		Note: counter must have a value between 1 and 9 inclusive.

\newcounter{foo}[counter] 			*\newcounter*
		Defines a new counter named {foo}. The counter is initialized
		to zero.  The optional argument [counter] causes the counter
		{foo} to be reset whenever the counter named in the optional
		argument is incremented.

\refstepcounter{counter}			*\refstepcounter*
		Command works like |\stepcounter|, except it also defines the
		current |\ref| value to be the result of \thecounter.

\roman{counter} 				*\roman* *\Roman*
\Roman{counter}
		Causes the value of the {counter} to be printed in Roman
		numerals.  The |\roman| command uses lower case Roman numerals,
		i.e., i, ii, iii..., while the |\Roman| command uses upper case
		Roman numerals, i.e., I, II, III....

\stepcounter{counter}				*\stepcounter*
		Adds one to the {counter} and resets all subsidiary counters.

\setcounter{counter}{value}			*\setcounter*
		Sets the value of the {counter} to that specified by the
		{value} argument.

\usecounter{counter} 				*\usecounter*
		Command is used in the second argument of the |list|
		environment to allow the {counter} specified to be used to
		number the list items.

\value{counter} 				*\value*
		Produces the value of the {counter} named in the mandatory
		argument. It can be used where LaTeX expects an integer or
		number, such as the second argument of a |\setcounter| or
		|\addtocounter| command, or in: >
			\hspace{\value{foo}\parindent}
<		It is useful for doing arithmetic with counters.

==============================================================================
3. Cross References				*latex-references*

One reason for numbering things like figures and equations is to refer the
reader to them, as in "See Figure 3 for more details."

|\label|		Assign a symbolic name to a piece of text
|\pageref|		Refer to a page number
|\ref|			Refer to a section, figure or similar


\label{key} 					*\label*
		Command appearing in ordinary text assigns to the {key} the
		number of the current sectional unit; one appearing inside a
		numbered environment assigns that number to the {key}.

		A {key} can consist of any sequence of letters, digits, or
		punctuation characters. Upper and lowercase letters are
		different.

		To avoid accidentally creating two labels with the same name,
		it is common to use labels consisting of a prefix and a suffix
		separated by a colon. The prefixes conventionally used are
			* 'cha' for chapters
			* 'sec' for lower-level sectioning commands
			* 'fig' for figures
			* 'tab' for tables
			* 'eq'  for equations
		Thus, a label for a figure would look like: >
			\label{fig:bandersnatch}

\pageref{key} 					*\pageref*
		Command produces the page number of the place in the text
		where the corresponding |\label| command appears.  ie. where
		\label{key} appears.

\ref{key}					*\ref*
		Command produces the number of the sectional unit, equation
		number, ... of the corresponding |\label| command.

==============================================================================
4. Definitions					*latex-definitions*

|\newcommand| 		Define a new command
|\newenvironment| 	Define a new environment
|\newtheorem| 		Define a new theorem-like environment
|\newfont| 		Define a new font name
\DeclareFixedFont     Define a new font switch	


\newcommand{cmd}[args]{definition}		*\newcommand* *\renewcommand*
\newcommand{cmd}[args][default]{definition}
\renewcommand{cmd}[args]{definition}
\renewcommand{cmd}[args][default]{definition}

These commands define (or redefine) a command.

{cmd}		A command name beginning with a |\\|. For |\newcommand| it must
		not be already defined and must not begin with |\end|; for
		|\renewcommand| it must already be defined.

{args}		An integer from 1 to 9 denoting the number of arguments of the
		command being defined. The default is for the command to have
		no arguments.

{default}	If this optional parameter is present, it means that the
		command's first argument is optional. The default value of the
		optional argument is default.

{definition}	The text to be substituted for every occurrence of {cmd}; a
		parameter of the form #n in {cmd} is replaced by the text of
		the nth argument when this substitution takes place.

       					*\newenvironment* *\renewenvironment*
\newenvironment{nam}[args]{begdef}{enddef}
\newenvironment{nam}[args][default]{begdef}{enddef}
\renewenvironment{nam}[args]{begdef}{enddef}

These commands define or redefine an environment.

{nam} 		The name of the environment. For |\newenvironment| there must
		be no currently defined environment by that name, and the
		command \nam must be undefined.  For |\renewenvironment| the
		environment must already be defined.

{args}		An integer from 1 to 9 denoting the number of arguments of
		the newly-defined environment. The default is no arguments.

{default} 	If this is specified, the first argument is optional, and
		default gives the default value for that argument.

{begdef} 	The text substituted for every occurrence of \begin{nam}; a
		parameter of the form #n in {cmd} is replaced by the text of
		the nth argument when this substitution takes place.

{enddef} 	The text substituted for every occurrence of \end{nam}. It
		may not contain any argument parameters.


\newtheorem{envname}{caption}[within]			*\newtheorem*
\newtheorem{envname}[numberedlike]{caption}

This command defines a theorem-like environment.

{envname}	The name of the environment to be defined. A string of
		letters. It must not be the name of an existing environment or
		counter.

{caption}	The text printed at the beginning of the environment, right
		before the number. This may simply say "Theorem", for example.

{within}	The name of an already defined counter, usually of a sectional
		unit. Provides a means of resetting the new theorem counter
		within the sectional unit.

{numberedlike}	The name of an already defined theorem-like environment.

The |\newtheorem| command may have at most one optional argument.


\newfont{cmd}{fontname} 				*\newfont*
		Defines the command name {cmd}, which must not be currently
		defined, to be a declaration that selects the font named
		{fontname} to be the current font.

\DeclareFixedFont{cmd}{encoding}{family}{series}{shape}{size}		
		Defines new command {cmd} which will switch to the declared
		font. Other attributes of this command are the same os
		for the \usefont command. Example
		    \DeclareFixedFont{\bold}{T1}{qbk}{b}{it}{11}

==============================================================================
5. Document Classes				*latex-classes*


\documentclass[options]{class}			*\documentclass*

Valid LaTeX document classes include:
	*article		*article-class*
	*report			*report-class*
	*letter			*letter-class*
	*book			*book-class*
	*slides			*slides-class*

All the standard classes (except slides) accept the following options for
selecting the typeface size (10 pt is default):

10pt, 11pt, 12pt

All classes accept these options for selecting the paper size (default is
letter):

a4paper, a5paper, b5paper, letterpaper, legalpaper, executivepaper

Miscellaneous options:

landscape 					*landscape*
	Selects landscape format. Default is portrait.

titlepage, notitlepage				*notitlepage*
		Selects if there should be a separate title page.

leqno						*leqno* *rqno*
		Equation number on left side of equations.  Default is
		right side.

fleqn						*fleqn*
		Displayed formulas flush left.  Default is centred.

openbib						*openbib*
		Use "open" bibliography format.

draft, final					*draft* *final*
		Mark/do not mark overfull boxes with a rule. Default is
		final.

These options are not available with the slides class:

oneside, twoside				*oneside* *twoside*
		Selects one- or twosided layout. Default is oneside,
		except for the book class.

openright, openany				*openright* *openany*
		Determines if a chapter should start on a right-hand page.
		Default is openright for book.

onecolumn, twocolumn				*onecolumn* *twocolumn*
		One or two columns.  Defaults to one column.

The slides class offers the option clock for printing the time at the bottom
of each |\note|.

If you specify more than one option, they must be separated by a comma.

\usepackage[options]{pkg} 			*\usepackage*
		Additional packages are loaded by this. If you
		specify more than one package, they must be separated by a
		comma.

Any options given in the |\documentclass| command that are unknown by the
selected document class are passed on to the packages loaded with |\usepackage|.

==============================================================================
6. Layout					*latex-layout*

Miscellaneous commands for controlling the general layout of the page.

|\flushbottom|		Make all text pages the same height.
|\onecolumn| 		Use one-column layout.
|\raggedbottom| 	Allow text pages of differing height.
|\twocolumn| 		Use two-column layout.

\flushbottom					*\flushbottom*
		Makes all text pages the same height, adding extra vertical
		space when necessary to fill out the page.  This is the
		standard if twocolumn mode is selected.

\onecolumn					*\onecolumn*
		Starts a new page and produces single-column output.

\raggedbottom					*\raggedbottom*
		Makes all pages the height of the text on that page.  No extra
		vertical space is added.

\twocolumn[text]				*\twocolumn*
		Starts a new page and produces two-column output.  If the
		optional [text] argument is present, it is typeset in
		one-column mode.

==============================================================================
7. Environments					*latex-environments*

						*\begin* *\end*
LaTeX provides a number of different paragraph-making environments. Each
environment begins and ends in the same manner: >

	\begin{environment-name}
	.
	.
	.
	\end{environment-name}
<
a. |array| 		Math arrays
b. |center| 		Centred lines
c. |description| 	Labelled lists
d. |enumerate|		Numbered lists
e. |eqnarray| 		Sequences of aligned equations
f. |equation| 		Displayed equation
g. |figure| 		Floating figures
h. |flushleft| 		Flushed left lines
i. |flushright| 	Flushed right lines
j. |itemize| 		Bulleted lists
k. |letter| 		Letters
l. |list| 		Generic list environment
m. |minipage| 		Miniature page
n. |picture| 		Picture with text, arrows, lines and circles
o. |quotation| 		Indented environment with paragraph indentation
p. |quote-l| 		Indented environment with no paragraph indentation
q. |tabbing| 		Align text arbitrarily
r. |table| 		Floating tables
s. |tabular| 		Align text in columns
t. |thebibliography| 	Bibliography or reference list
u. |theorem| 		Theorems, lemmas, etc
v. |titlepage| 		For hand crafted title pages
x. |verbatim| 		Simulating typed input
y. |verse| 		For poetry and other things

==============================================================================
 a. array					*array*
>
	\begin{array}{col1col2...coln}
		column 1 entry & column 2 entry ... & column n entry \\
		.
		.
		.
	\end{array}

Math arrays are produced with the |array| environment. It has a single mandatory
argument describing the number of columns and the alignment within them. Each
column, coln, is specified by a single letter that tells how items in that row
should be formatted.
	* c -- for centred
	* l -- for flush left
	* r -- for flush right
Column entries must be separated by an |&|. Column entries may include other
LaTeX commands. Each row of the array must be terminated with the string |\\|.

Note that the |array| environment can only be used in |math-mode|, so normally
it is used inside an |equation| environment.

==============================================================================
b. center					*center*
>
	\begin{center}
		Text on line 1 \\
		Text on line 2 \\
		.
		.
		.
	\end{center}

The |\center| environment allows you to create a paragraph consisting of lines
that are centred within the left and right margins on the current page. Each
line must be terminated with the string |\\|.

\centering					*\centering*
		This declaration corresponds to the |center| environment. This
		declaration can be used inside an environment such as
		|quote-l| or in a |\parbox|. The text of a |figure| or |table|
		can be centred on the page by putting a |\centering| command
		at the beginning of the |figure| or |table| environment.
		Unlike the |center| environment, the |\centering| command does
		not start a new paragraph; it simply changes how LaTeX formats
		paragraph units. To affect a paragraph unit's format, the
		scope of the declaration must contain the blank line or |\end|
		command (of an environment like |quote-l|) that ends the
		paragraph unit.

==============================================================================
c. description					*description*
>
	\begin{description}
		\item [label] First item
		\item [label] Second item
		.
		.
		.
	\end{description}

The |description| environment is used to make labelled lists. The label is
bold face and flushed right.

==============================================================================
d. enumerate					*enumerate*
>
	\begin{enumerate}
		\item First item
		\item Second item
		.
		.
		.
	\end{enumerate}

The |enumerate| environment produces a numbered list.  Enumerations can be
nested within one another, up to four levels deep.  They can also be nested
within other paragraph-making environments.

\item		Each item of an enumerated list begins with an |\item|
		command. There must be at least one |\item| command
		within the environment.

The |enumerate| environment uses the |\enumi| through |\enumiv| counters (see
section |latex-counters|). The type of numbering can be changed by redefining
\theenumi etc.

==============================================================================
e. eqnarray					*eqnarray*
>
	\begin{eqnarray}
		math formula 1 \\
		math formula 2 \\
		.
		.
		.
	\end{eqnarray}

The |eqnarray| environment is used to display a sequence of equations or
inequalities. It is very much like a three-column |array| environment, with
consecutive rows separated by |\\| and consecutive items within a row separated
by an |&|.

\nonumber					*\nonumber*
		An equation number is placed on every line unless that
		line has a |\nonumber| command.

\lefteqn					*\lefteqn*
		The command |\lefteqn| is used for splitting long
		formulas across lines.  It typesets its argument in
		display style flush left in a box of zero width.

==============================================================================
f. equation	 				*equation*
>
	\begin{equation}
		math formula
	\end{equation}

The |equation| environment centres your equation on the page and places the
equation number in the right margin.

==============================================================================
g. figure					*figure*
>
	\begin{figure}[placement]
		body of the figure
		\caption{figure title}
	\end{figure}

Figures are objects that are not part of the normal text, and are usually
"floated" to a convenient place, like the top of a page. Figures will not be
split between two pages.

The optional argument [placement] determines where LaTeX will try to place
your figure. There are four places where LaTeX can possibly put a float:

h (Here)		at the position in the text where the figure
			environment appears.
t (Top)			at the top of a text page.
b (Bottom)		at the bottom of a text page.
p (Page of floats)	on a separate float page, which is a page containing
			no text, only floats.

The standard |report-class| and |article-class| use the default placement
[tbp].

The body of the |figure| is made up of whatever text, LaTeX commands, etc.  you
wish.

The \caption command allows you to title your figure.

==============================================================================
h. flushleft					*flushleft*
>
	\begin{flushleft}
		Text on line 1 \\
		Text on line 2 \\
		.
		.
		.
	\end{flushleft}

The |flushleft| environment allows you to create a paragraph consisting of
lines that are flushed left, to the left-hand margin. Each line must be
terminated with the string |\\|.

\raggedright					*\raggedright*
		This declaration corresponds to the |flushleft| environment.
		This declaration can be used inside an environment such as
		|quote-l| or in a |\parbox|.  Unlike the |flushleft|
		environment, the |\raggedright| command does not start a new
		paragraph; it simply changes how LaTeX formats paragraph
		units. To affect a paragraph unit's format, the scope of the
		declaration must contain the blank line or |\end| command (of
		an environment like |quote-l|) that ends the paragraph unit.

==============================================================================
i. flushright					*flushright*
>
	\begin{flushright}
		Text on line 1 \\
		Text on line 2 \\
		.
		.
		.
 	\end{flushright}

The |flushright| environment allows you to create a paragraph consisting of
lines that are flushed right, to the right-hand margin. Each line must be
terminated with the string |\\|.

\raggedleft					*\raggedleft*
		This declaration corresponds to the |flushright| environment.
		This declaration can be used inside an environment such as
		|quote-l| or in a |\parbox|.  Unlike the |flushright|
		environment, the |\raggedleft| command does not start a new
		paragraph; it simply changes how LaTeX formats paragraph
		units. To affect a paragraph unit's format, the scope of the
		declaration must contain the blank line or |\end| command (of
		an environment like |quote-l|) that ends the paragraph unit.

==============================================================================
j. itemize					*itemize*
>
	\begin{itemize}
		\item First item
		\item Second item
		.
		.
		.
	\end{itemize}

The |itemize| environment produces a "bulleted" list.  Itemizations can be
nested within one another, up to four levels deep.  They can also be nested
within other paragraph-making environments.

\item						*\item*
		Each item of an itemized list begins with an |\item| command.
		There must be at least one |\item| command within the
		environment.

The itemize environment uses the |\itemi| through |\itemiv| counters (see
section |latex-counters|). The type of numbering can be changed by redefining
\theitemi etc.

==============================================================================
k. letter					*\letter*

This environment is used for creating letters. See section |latex-letters|.

==============================================================================
l. list						*list*

The |list| environment is a generic environment which is used for defining many
of the more specific environments. It is seldom used in documents, but often
in macros.
>
	\begin{list}{label}{spacing}
		\item First item
		\item Second item
		.
		.
		.
	\end{list}

'label'		The {label} argument specifies how items should be labelled.
		This argument is a piece of text that is inserted in a box to
		form the {label}.  This argument can and usually does contain
		other LaTeX commands.

'spacing'	The {spacing} argument contains commands to change the spacing
		parameters for the |list|. This argument will most often be
		null, i.e., {}. This will select all default spacing which
		should suffice for most cases.

==============================================================================
m. minipage					*minipage*
>
	\begin{minipage}[position]{width}
		text
	\end{minipage}

The |minipage| environment is similar to a |\parbox| command. It takes the
same optional [position] argument and mandatory {width} argument. You may use
other paragraph-making environments inside a |minipage|.  Footnotes in a
minipage environment are handled in a way that is particularly useful for
putting footnotes in figures or tables. A |\footnote| or |\footnotetext|
command puts the footnote at the bottom of the minipage instead of at the
bottom of the page, and it uses the |\mpfootnote| counter instead of the
ordinary footnote counter. See sections |latex-counters| and
|latex-footnotes|.

NOTE: Don't put one |minipage| inside another if you are using footnotes; they
may wind up at the bottom of the wrong minipage.

==============================================================================
n. picture					*picture*
>
		 	   size		  position
	\begin{picture}(width,height)(x offset,y offset)
		.
		.
		picture commands
		.
		.
	\end{picture}

The |picture| environment allows you to create just about any kind of picture
you want containing text, lines, arrows and circles. You tell LaTeX where to
put things in the picture by specifying their coordinates. A coordinate is a
number that may have a decimal point and a minus sign -- a number like 5, 2.3
or -3.1416. A coordinate specifies a length in multiples of the unit length
|\unitlength|, so if |\unitlength| has been set to 1cm, then the coordinate
2.54 specifies a length of 2.54 centimetres. You can change the value of
|\unitlength| anywhere you want, using the |\setlength| command, but strange
things will happen if you try changing it inside the |picture| environment.

A position is a pair of coordinates, such as (2.4,-5), specifying the point
with x-coordinate 2.4 and y-coordinate -5. Coordinates are specified in the
usual way with respect to an origin, which is normally at the lower-left
corner of the |picture|.
Note that when a position appears as an argument, it is not enclosed in
braces; the parentheses serve to delimit the argument.

The |picture| environment has one mandatory argument, which is a position.  It
specifies the size of the picture. The environment produces a rectangular box
with width and height determined by this argument's x- and y-coordinates.

The |picture| environment also has an optional position argument, following
the size argument, that can change the origin. (Unlike ordinary optional
arguments, this argument is not contained in square brackets.) The optional
argument gives the coordinates of the point at the lower-left corner of the
picture (thereby determining the origin).  For example, if |\unitlength| has
been set to 1mm, the command: >
	\begin{picture}(100,200)(10,20)
>
produces a picture of width 100 millimetres and height 200 millimetres, whose
lower-left corner is the point (10,20) and whose upper-right corner is
therefore the point (110,220). When you first draw a picture, you will omit
the optional argument, leaving the origin at the lower-left corner. If you
then want to modify your picture by shifting everything, you just add the
appropriate optional argument.

The environment's mandatory argument determines the nominal size of the
picture. This need bear no relation to how large the picture really is; LaTeX
will happily allow you to put things outside the picture, or even off the
page. The picture's nominal size is used by LaTeX in determining how much room
to leave for it.

Everything that appears in a picture is drawn by the |\put| command. The
command: >
	\put (11.3,-.3){...}

puts the object specified by ... in the picture, with its
reference point at coordinates (11.3,-.3). The reference points for various
objects will be described below.

The |\put| creates an LR box (|lrbox|). You can put anything in the text
argument of the |\put| that you'd put into the argument of an |\mbox| and
related commands. When you do this, the reference point will be the lower left
corner of the box.

Picture commands:
|\circle|		Draw a circle
|\dashbox|		Draw a dashed box
|\frame|		Draw a frame around an object
|\framebox(picture)|	Draw a box with a frame around it
|\line|			Draw a straight line
|\linethickness|	Set the line thickness
|\makebox(picture)|	Draw a box of the specified size
|\multiput|		Draw multiple instances of an object
|\oval|			Draw an ellipse
|\put|			Place an object at a specified place
|\shortstack|		Make a pile of objects
|\vector|		Draw a line with an arrow

\circle[*]{diameter}				*\circle*
		Command produces a circle with a {diameter} as close to the
		specified one as possible. If the *-form of the command is
		used, LaTeX draws a solid circle.
		Note: only circles up to 40 pt can be drawn.


\dashbox{dashlength}(width,height){...} 	*\dashbox*
		Draws a box with a dashed line.  The |\dashbox| has an extra
		argument which specifies the width of each dash.  A dashed box
		looks best when the width and height are multiples of the
		{dashlength}.

\frame{...} 					*\frame*
		Puts a rectangular frame around the object specified in the
		argument. The reference point is the bottom left corner of the
		frame. No extra space is put between the frame and the object.

\framebox(width,height)[position]{...}		*\picture-framebox*
		The |\framebox| command is exactly the same as the
		|picture-makebox| command, except that it puts a frame around
		the outside of the box that it creates.  The |\framebox|
		command produces a rule of thickness |\fboxrule|, and leaves a
		space |\fboxsep| between the rule and the contents of the box.

\line(x slope,y slope){length} 			*\line*
		Draws a line of the specified length and slope.
		Note: LaTeX can only draw lines with slope = x/y, where x and
		y have integer values from -6 through 6.

\linethickness{dimension}			*\linethickness*
		Declares the thickness of horizontal and vertical lines in a
		|picture| environment to be dimension, which must be a
		positive length. It does not affect the thickness of slanted
		lines (|\line|) and circles (|circle|), or the quarter circles
		drawn by |\oval| to form the corners of an oval.

\makebox(width,height)[position]{...} 		*picture-makebox*
		The makebox command for the |picture| environment is similar
		to the normal |\makebox| command except that you must specify
		a width and height in multiples of |\unitlength|.
		The optional argument, [position], specifies the quadrant that
		your text appears in. You may select up to two of the
		following:
			t - Moves the item to the top of the rectangle
			b - Moves the item to the bottom
			l - Moves the item to the left
			r - Moves the item to the right

						*\multiput*
\multiput(x coord,y coord)(delta x,delta y){no of copies}{object}
		This command can be used when you are putting the same
		object in a regular pattern across a picture.

\oval(width,height)[portion] 			*\oval*
		Produces a rectangle with rounded corners. The optional
		argument, [portion], allows you to select part of the oval.
			t - top portion
			b - bottom portion
			r - right portion
			l - left portion
		Note: the "corners" of the oval are made with quarter circles
		with a maximum radius of 20 pt, so large "ovals" will look
		more like boxes with rounded corners.

\put(x coord,y coord){ ... } 			*\put*
		Places the item specified by the mandatory argument at the
		given coordinates.

\shortstack[position]{... \\ ... \\ ...} 	*\shortstack*
		The |\shortstack| command produces a stack of objects.
		The valid positions are:
			r - right of the stack
			l - left of the stack
			c - centre of the stack (default)

\vector(x slope,y slope){length} 		*\vector*
		Draws a line with an arrow of the specified length and slope.
		The x and y values must lie between -4 and +4, inclusive.

==============================================================================
o. quotation					*quotation*
 >
	\begin{quotation}
		text
	\end{quotation}

The margins of the |quotation| environment are indented on the left and the
right. The text is justified at both margins and there is paragraph
indentation. Leaving a blank line between text produces a new paragraph.

==============================================================================
p. quote					*quote-l*
>
	\begin{quote}
		text
	\end{quote}

The margins of the |quote-l| environment are indented on the left and the right.
The text is justified at both margins.  Leaving a blank line between text
produces a new paragraph.

==============================================================================
q. tabbing					*tabbing*
>
	\begin{tabbing}
	text \= more text \= still more text \= last text \\
	second row \>  \> more \\
	.
	.
	.
	\end{tabbing}

The |tabbing| environment provides a way to align text in columns. It works by
setting tab stops and tabbing to them much the way you do with an ordinary
typewriter.

It is best suited for cases where the width of each column is constant and
known in advance.

This environment can be broken across pages, unlike the |tabular| environment.
The following commands can be used inside a tabbing environment:

				*tab=*
\= 		Sets a tab stop at the current position.

						*tab>*
\> 		Advances to the next tab stop.

						*tab<*
\< 		This command allows you to put something to the left of the
		local margin without changing the margin. Can only be used at
		the start of the line.

						*tab+*
\+ 		Moves the left margin of the next and all the following
		commands one tab stop to the right.

						*tab-*
\- 		Moves the left margin of the next and all the following
		commands one tab stop to the left.

						*tab'*
\' 		Moves everything that you have typed so far in the current
		column, i.e.  everything from the most recent \> (|tab>|), \<
		(|tab<|), \' (|tab'|), |\\|, or |\kill| command, to the right
		of the previous column, flush against the current column's tab
		stop.

						*tab`*
\`		Allows you to put text flush right against any tab stop,
		including tab stop 0. However, it can't move text to the right
		of the last column because there's no tab stop there. The \`
		(|tab`|) command moves all the text that follows it, up to the
		|\\| or \end{tabbing} command that ends the line, to the right
		margin of the tabbing environment. There must be no \>
		(|tab>|) or \' (|tab'|) command between the \` (|tab`|) and
		the command that ends the line.

						*\kill*
\kill 		Sets tab stops without producing text. Works just like |\\|
		except that it throws away the current line instead of
		producing output for it. The effect of any \= (|tab=|), \+
		(|tab+|) or \- (|tab-|) commands in that line remain in
		effect.

						*\pushtabs*
\pushtabs	Saves all current tab stop positions. Useful for temporarily
		changing tab stop positions in the middle of a tabbing
		environment. Also restores the tab stop positions saved by the
		last |\pushtabs|.

						*taba*
\a		In a tabbing environment, the commands \= (|tab=|), \'
		(|tab'|) and \` (|tab`|) do not produce accents as normal.
		Instead, the commands \a=, \a' and \a` are used.

This example typesets a Pascal function in a traditional format:
>
        \begin{tabbing}
        function \= fact(n : integer) : integer;\\
                 \> begin \= \+ \\
                       \> if \= n $>$ 1 then \+ \\
                                fact := n * fact(n-1) \- \\
                          else \+ \\
                                fact := 1; \-\- \\
                    end;\\
        \end{tabbing}

==============================================================================
r. table					*\table*
>
	\begin{table}[placement]
		body of the table
		\caption{table title}
	\end{table}

Tables are objects that are not part of the normal text, and are usually
"floated" to a convenient place, like the top of a page. Tables will not be
split between two pages.

The optional argument [placement] determines where LaTeX will try to place
your table. There are four places where LaTeX can possibly put a float:

	h (Here)		at the position in the text where the table
				environment appears.
	t (Top)			at the top of a text page.
	b (Bottom)		at the bottom of a text page.
	p (Page of floats)	on a separate float page, which is a page
				containing no text, only floats.

The standard |report-class| and |article-class| use the default placement [tbp].

The body of the table is made up of whatever text, LaTeX commands, etc., you
wish.

The \caption command allows you to title your table.

==============================================================================
s. tabular					*tabular*
>
	\begin{tabular}[pos]{cols}
		column 1 entry & column 2 entry ... & column n entry \\
		.
		.
		.
	\end{tabular}

or
>
	\begin{tabular*}{width}[pos]{cols}
		column 1 entry & column 2 entry ... & column n entry \\
		.
		.
		.
	\end{tabular*}

These environments produce a box consisting of a sequence of rows of items,
aligned vertically in columns. The mandatory and optional arguments consist
of:

{width}	Specifies the width of the tabular* environment. There must be
	rubber space between columns that can stretch to fill out the
	specified width.

[pos]	Specifies the vertical position; default is alignment on the
	centre of the environment.
		t - align on top row
		b - align on bottom row

{cols}	Specifies the column formatting. It consists of a sequence of
	the following specifiers, corresponding to the sequence of
	columns and intercolumn material.
		l - A column of left-aligned items.

		r - A column of right-aligned items.

		c - A column of centred items.

		| - A vertical line the full height and depth of the
		environment.

		@{text} - This inserts text in every row. An @-expression
		suppresses the intercolumn space normally inserted
		between columns; any desired space between the
		inserted text and the adjacent items must be included
		in text. An \extracolsep{wd} command in an
		@-expression causes an extra space of width {wd} to
		appear to the left of all subsequent columns, until
		countermanded by another |\extracolsep| command. Unlike
		ordinary intercolumn space, this extra space is not
		suppressed by an @-expression. An |\extracolsep|
		command can be used only in an @-expression in the
		cols argument.

		p{wd} - Produces a column with each item typeset in a |\parbox|
		of width {wd}, as if it were the argument of a
		\parbox[t]{wd} command. However, a |\\| may not appear
		in the item, except in the following situations:
		1. inside an environment like |minipage|, |array|, or
		|tabular|.
		2. inside an explicit |\parbox|.
		3. in the scope of a |\centering|, |\raggedright|, or
		|\raggedleft| declaration. The latter declarations must
		appear inside braces or an environment when used in a
		p-column element.

		{num}{cols} - Equivalent to num copies of cols, where num is any positive
		integer and cols is any list of column-specifiers,
		which may contain another -expression.

These commands can be used inside a tabular environment:

|\cline|		Draw a horizontal line spanning some columns.
|\hline|		Draw a * horizontal line spanning all columns.
|\multicolumn|		Make an item spanning * several columns.
|\vline|		Draw a vertical line.


\cline{i-j}					*\cline*
		The |\cline| command draws horizontal lines across the columns
		specified, beginning in column i and ending in column j,
		which are identified in the mandatory argument.

\hline						*\hline*
		The |\hline| command will draw a horizontal line the width of
		the table.  It's most commonly used to draw a line at the top,
		bottom, and between the rows of the table.

\multicolumn{cols}{pos}{text} 			*\multicolumn*
		The |\multicolumn| is used to make an entry that spans several
		columns.  The first mandatory argument, {cols}, specifies the
		number of columns to span. The second mandatory argument,
		{pos}, specifies the formatting of the entry:
			c - centered
			l - flushleft
			r - flushright.
		The third mandatory argument, {text}, specifies what text is
		to make up the entry.

\vline						*\vline*
		The |\vline| command will draw a vertical line extending the
		full height and depth of its row. An |\hfill| command can be
		used to move the line to the edge of the column. It can also
		be used in an @-expression.

==============================================================================
t. thebibliography				*\thebibliography*
>
	\begin{thebibliography}{widestlabel}
		\bibitem[label]{cite_key}
		.
		.
		.
	\end{thebibliography}

The |\thebibliography| environment produces a bibliography or reference list.

In the |article-class|, this reference list is labelled "References"; in the
|report-class|, it is labelled "Bibliography".

{widestlabel}	Text that, when printed, is approximately as wide as the
 		widest item label produces by the |\bibitem| commands.

|\bibitem|		Specify a bibliography item.
|\cite|			Refer to a bibliography item.
|\nocite|		Include an item in the bibliography.
|BibTeX|		Automatic generation of bibliographies.

\bibitem					*\bibitem*
\bibitem[label]{citekey}
		The |\bibitem| command generates an entry labelled by [label].
		If the [label] argument is missing, a number is generated as
		the label, using the |\enumi| counter.  The {citekey} is any
		sequence of letters, numbers, and punctuation symbols not
		containing a comma. This command writes an entry on the `.aux'
		file containing {citekey} and the item's label. When this
		`.aux' file is read by the \begin{document} command, the
		item's label is associated with {citekey}, causing the
		reference to {citekey} by a |\cite| command to produce the
		associated label.

\cite						*\cite*
\cite[text]{keylist}
		The {keylist} argument is a list of citation keys.  This
		command generates an in-text citation to the references
		associated with the keys in {keylist} by entries on the `.aux'
		file read by the \begin{document} command.
		The optional text argument will appear after the
		citation, i.e.: >
			\cite[p.2]{knuth}
<		might produce `[Knuth, p. 2]'.

\nocite						*\nocite*
\nocite{keylist}
		The |\nocite| command produces no text, but writes
		{keylist}, which is a list of one or more citation
		keys, on the `.aux' file.

BibTeX						*BibTeX* *bibtex*
						*\bibliographystyle*
If you use the BibTeX program by Oren Patashnik (highly recommended if you
need a bibliography of more than a couple of titles) to maintain your
bibliography, you don't use the |thebibliography| environment.  Instead, you
include the lines:
>
	\bibliographystyle{style}
	\bibliography{bibfile}

where {style} refers to a file style.bst, which defines how your citations
will look. The standard styles distributed with BibTeX are:

{alpha}	Sorted alphabetically. Labels are formed from name of author and year
	of publication.
{plain} Sorted alphabetically. Labels are numeric.
{unsrt} Like plain, but entries are in order of citation.
{abbrv} Like plain, but more compact labels.

In addition, numerous other BibTeX style files exist tailored to the demands
of various publications.

						*\bibliography*
The argument to |\bibliography| refers to the file bibfile.bib, which should
contain your database in BibTeX format. Only the entries referred to via
|\cite| and |\nocite| will be listed in the bibliography.

==============================================================================
u. theorem					*theorem*
>
	\begin{theorem}
		theorem text
	\end{theorem}

The |theorem| environment produces "Theorem x" in boldface followed by your
theorem text.

==============================================================================
v. titlepage					*titlepage*
>
	\begin{titlepage}
		text
	\end{titlepage}

The |titlepage| environment creates a title page, i.e. a page with no printed
page number or heading. It also causes the following page to be numbered page
one. Formatting the title page is left to you. The |\today| command comes in
handy for title pages.

Note that you can use the |\maketitle| to produce a standard title page.

==============================================================================
x. verbatim					*verbatim*
>
	\begin{verbatim}
		text
	\end{verbatim}

The |verbatim| environment is a paragraph-making environment that gets LaTeX
to print exactly what you type in. It turns LaTeX into a typewriter with
carriage returns and blanks having the same effect that they would on a
typewriter.

\verb						*\verb*
\verb char literal_text char
\verb*char literal_text char
		Typesets literal_text exactly as typed, including
		special characters and spaces, using a typewriter |\tt|
		type style. There may be no space between |\verb| or
		|\verb|* and char (space is shown here only for
		clarity).  The *-form differs only in that spaces are
		printed as `\verb*| |\'.

==============================================================================
y. verse					*verse*
>
	\begin{verse}
		text
	\end{verse}

The |verse| environment is designed for poetry, though you may find other uses
for it.

The margins are indented on the left and the right. Separate the lines of each
stanza with |\\|, and use one or more blank lines to separate the stanzas.

==============================================================================
8. Footnotes					*latex-footnotes*

Footnotes can be produced in one of two ways. They can be produced with one
command, the |\footnote| command. They can also be produced with two commands,
the |\footnotemark| and the |\footnotetext| commands. See the specific command for
information on why you would use one over the other.

|\footnote| 	Insert a footnote
|\footnotemark|	Insert footnote mark only
|\footnotetext|	Insert footnote text only

\footnote[number]{text}				*\footnote*
		Command places the numbered footnote text at the bottom of the
		current page. The optional argument, number, is used to change
		the default footnote number.  This command can only be used in
		outer paragraph mode; i.e., you cannot use it in sectioning
		commands like |\chapter|, in |\figure|, |\table| or in a
		|\tabular| environment.

\footnotemark					*\footnotemark*
		Command puts the footnote number in the text. This command can
		be used in inner paragraph mode. The text of the footnote is
		supplied by the |\footnotetext| command.
		This command can be used to produce several consecutive
		footnote markers referring to the same footnote by using
>
			\footnotemark[\value{footnote}]
<
		after the first |\footnote| command.

\footnotetext[number]{text}			*\footnotetext*
		Command produces the text to be placed at the bottom of the
		page. This command can come anywhere after the |\footnotemark|
		command. The |\footnotetext| command must appear in outer
		paragraph mode.  The optional argument, number, is used to
		change the default footnote number.

==============================================================================
9. Lengths					*latex-lengths*

A length is a measure of distance. Many LaTeX commands take a length as an
argument.

|\newlength|	Define a new length.
|\setlength|	Set the value of a length.
|\addtolength|	Add a quantity to a length.
|\settodepth|	Set a length to  the depth of something.
|\settoheight|	Set a length to the height of  something.
|\settowidth|	Set a length to the width of something.
|pre-lengths|	Lengths that are, like, predefined.

\newlength{\gnat}				*\newlength*
		The |\newlength| command defines the mandatory argument, \gnat,
		as a length command with a value of 0in. An error occurs if a
		\gnat command already exists.

\setlength{\gnat}{length}			*\setlength*
		The |\setlength| command is used to set the value of a \gnat
		command. The {length} argument can be expressed in any terms
		of length LaTeX understands, i.e., inches (in), millimetres
		(mm), points (pt), etc.

\addtolength{\gnat}{length} 			*\addtolength*
		The |\addtolength| command increments a \gnat by the amount
		specified in the {length} argument. It can be a negative
		amount.

\settodepth{\gnat}{text} 			*\settodepth*
		The |\settodepth| command sets the value of a \gnat command
		equal to the depth of the {text} argument.

\settoheight{\gnat}{text} 			*\settoheight*
		The |\settoheight| command sets the value of a \gnat command
		equal to the height of the {text} argument.

\settowidth{\gnat}{text}			*\settowidth*
		The |\settowidth| command sets the value of a \gnat command
		equal to the width of the {text} argument.

Predefined lengths				*pre-lengths*

\width 						*\width*
\height						*\height*
\depth						*\depth*
\totalheight					*\totalheight*
		These length parameters can be used in the arguments of the
		box-making commands See section Spaces & Boxes. They specify
		the natural width etc.  of the text in the box.
		\totalheight equals \height + \depth.
		To make a box with the text stretched to double the natural
		size, e.g., say: >
			\makebox[2\width]{Get a stretcher}

==============================================================================
10. Letters					*latex-letters*

You can use LaTeX to typeset letters, both personal and business. The letter
document class is designed to make a number of letters at once, although you
can make just one if you so desire.

Your `.tex' source file has the same minimum commands as the other document
classes, i.e., you must have the following commands as a minimum: >
	\documentclass{letter}
	\begin{document}
		...
		letters
		...
	\end{document}

Each letter is a letter environment, whose argument is the name and address of
the recipient. For example, you might have: >
	\begin{letter}
		{Mr. Joe Smith\\
		2345 Princess St.  \\
		Edinburgh, EH1 1AA}
		...
	\end{letter}

The letter itself begins with the |\opening| command.  The text of the letter
follows. It is typed as ordinary LaTeX input.  Commands that make no sense in
a letter, like |\chapter|, do not work. The letter closes with a |\closing|
command.

After the closing, you can have additional material. The |\cc| command produces
the usual "cc: ...". There's also a similar |\encl| command for a list of
enclosures. With both these commands, use|\\| to separate the items.

These commands are used with the letter class:
|\address|	Your return address.
|\cc|		Cc list.  closing Saying goodbye.
|\encl|		List of enclosed material.
|\location|	Your organisation's address.
|\makelabels|	Making address labels.
|\name|		Your name, for the return address.
|\opening|	Saying hello.
|\ps|		Adding a postscript.
|\signature|	Your signature.
|\startbreaks|	Allow page breaks.
|\stopbreaks|	Disallow page breaks.
|\telephone|	Your phone number.

\address{Return address}			*\address*
		The return address, as it should appear on the letter and the
		envelope.  Separate lines of the address should be separated
		by |\\| commands. If you do not make an |\address| declaration,
		then the letter will be formatted for copying onto your
		organisation's standard letterhead. (See section Overview of
		LaTeX and Local Guide, for details on your local
		implementation). If you give an |\address| declaration, then
		the letter will be formatted as a personal letter.

\cc{Kate Schechter\\Rob McKenna}		*\cc*
		Generate a list of other persons the letter was sent to. Each
		name is printed on a separate line.

\closing{text}					*\closing*
		The letter closes with a |\closing| command, i.e., >
			\closing{Best Regards,} \encl{CV\\Certificates}
<		Generate a list of enclosed material.

\location{address}				*\location*
		This modifies your organisation's standard address. This only
		appears if the firstpage pagestyle is selected.

\makelabels{number}				*\makelabels*
		If you issue this command in the preamble, LaTeX will create a
		sheet of address labels. This sheet will be output before the
		letters.

\name{June Davenport}				*\name*
		Your name, used for printing on the envelope together with the
		return address.

\opening{text}					*\opening*
		The letter begins with the |\opening| command. The mandatory
		argument, text, is whatever text you wish to start your
		letter, i.e., >
			\opening{Dear Joe,}

\ps						*\ps*
		Use this command before a postscript.

\signature{Harvey Swick}			*\signature*
		Your name, as it should appear at the end of the letter
		underneath the space for your signature. Items that should go
		on separate lines should be separated by |\\| commands.

\startbreaks					*\startbreaks*
		Used after a |\stopbreaks| command to allow page breaks again.

\stopbreaks					*\stopbreaks*
		Inhibit page breaks until a |\startbreaks| command occurs.

\telephone{number}				*\telephone*
		This is your telephone number. This only appears if the
		firstpage pagestyle is selected.

==============================================================================
11. Line & Page Breaking			*latex-breaking*

The first thing LaTeX does when processing ordinary text is to translate your
input file into a string of glyphs and spaces. To produce a printed document,
this string must be broken into lines, and these lines must be broken into
pages. In some environments, you do the line breaking yourself with the |\\|
command, but LaTeX usually does it for you.

|\\| 			Start a new line
|hyph-| 		Insert explicit hyphenation
|\cleardoublepage| 	Start a new right-hand page
|\clearpage| 		Start a new page
|\enlargethispage| 	Enlarge the current page a bit
|\fussy| 		Be fussy about line breaking
|\hyphenation| 		Tell LaTeX how to hyphenate a word
|\linebreak| 		Break the line
|\newline| 		Break the line prematurely
|\newpage| 		Start a new page
|\nolinebreak| 		Don't break the current line
|\nointerlineskip|	Dont' make a space between lines
|\nopagebreak| 		Don't make a page break here
|\pagebreak| 		Please make a page break here
|\sloppy| 		Be sloppy about line breaking

\\[*][extraspace]				*\\* *\\\\*
		The |\\| command tells LaTeX to start a new line. It has an
		optional argument, [extraspace], that specifies how much extra
		vertical space is to be inserted before the next line. This
		can be a negative amount.
		The \\* command is the same as the ordinary |\\| command
		except that it tells LaTeX not to start a new page after the
		line.

\-						*hyph-*
		The \- command tells LaTeX that it may hyphenate the word at
		that point.  LaTeX is very good at hyphenating, and it will
		usually find all correct hyphenation points. The \- command is
		used for the exceptional cases.
		Note: when you insert \- commands in a word, the word will
		only be hyphenated at those points and not at any of the
		hyphenation points that LaTeX might otherwise have chosen.

\cleardoublepage				*\cleardoublepage*
		The |\cleardoublepage| command ends the current page and causes
		all figures and tables that have so far appeared in the input
		to be printed.  In a two-sided printing style (|twoside|), it
		also makes the next page a right-hand (odd-numbered) page,
		producing a blank page if necessary.

\clearpage					*\clearpage*
		The |\clearpage| command ends the current page and causes all
		figures and tables that have so far appeared in the input to
		be printed.

\enlargethispage{size} 				*\enlargethispage*
\enlargethispage*{size}
		Enlarge the textheight for the current page by the
		specified amount; e.g.: >

			\enlargethispage{\baselineskip}
<
		will allow one additional line.  The starred form
		tries to squeeze the material together on the page as
		much as possible. This is normally used together with
		an explicit |\pagebreak|.

\fussy						*\fussy*
		This declaration (which is the default) makes TeX more fussy
		about line breaking. This can avoids too much space between
		words, but may produce overfull boxes.  This command cancels
		the effect of a previous |\sloppy| command.

\hyphenation{words}				*\hyphenation*
		The |\hyphenation| command declares allowed hyphenation points,
		where words is a list of words, separated by spaces, in which
		each hyphenation point is indicated by a - character.

\linebreak[number]				*\linebreak*
		The |\linebreak| command tells LaTeX to break the current line
		at the point of the command. With the optional argument,
		number, you can convert the |\linebreak| command from a demand
		to a request. The [number] must be a number from 0 to 4. The
		higher the number, the more insistent the request is.  The
		|\linebreak| command causes LaTeX to stretch the line so it
		extends to the right margin.

\newline					*\newline*
		The |\newline| command breaks the line right where it is. It
		can only be used in paragraph mode.

\newpage					*\newpage*
		The |\newpage| command ends the current page.

\nolinebreak[number]				*\nolinebreak*
		The |\nolinebreak| command prevents LaTeX from breaking the
		current line at the point of the command. With the optional
		argument, [number], you can convert the |\nolinebreak| command
		from a demand to a request. The [number] must be a number from 0
		to 4. The higher the number, the more insistent the request
		is.

\nointerlineskip				*\nointerlineskip*
		Do not make a space between boxes in vertical mode and lines.
		For example:
		    \vbox{\hbox{line_1}|\nointerlineskip|\hbox{line_2}} 
		will place the two horizontal boxes without vertical skip. Can
		be also used after |\\|, however placing it before |\newline|
		raise an error. 
		

\nopagebreak[number]				*\nopagebreak*
		The |\nopagebreak| command prevents LaTeX from breaking the
		current page at the point of the command. With the optional
		argument, [number], you can convert the |\nopagebreak| command
		from a demand to a request. The [number] must be a number from
		0 to 4. The higher the number, the more insistent the request
		is.

\pagebreak[number]				*\pagebreak*
		The |\pagebreak| command tells LaTeX to break the current page
		at the point of the command. With the optional argument,
		[number], you can convert the |\pagebreak| command from a
		demand to a request. The [number] must be a number from 0 to
		4. The higher the number, the more insistent the request is.

\sloppy						*\sloppy*
		This declaration makes TeX less fussy about line breaking.
		This can prevent overfull boxes, but may leave too much space
		between words.
		Lasts until a |\fussy| command is issued.

==============================================================================
12. Making Paragraphs				*latex-paragraphs*

A paragraph is ended by one or more completely blank lines -- lines not
containing even a |\%|. A blank line should not appear where a new paragraph
cannot be started, such as in math mode or in the argument of a sectioning
command.

|\indent| 	Indent this paragraph.
|\noindent| 	Do not indent this paragraph.
|\par| 		Another way of writing a blank line.

\indent 					*\indent*
		This produces a horizontal space whose width equals the width
		of the paragraph indentation. It is used to add paragraph
		indentation where it would otherwise be suppressed.

\noindent 					*\noindent*
		When used at the beginning of the paragraph, it suppresses the
		paragraph indentation. It has no effect when used in the
		middle of a paragraph.

\par						*\par*
		Equivalent to a blank line; often used to make command or
		environment definitions easier to read.

==============================================================================
13. Margin Notes				*latex-margin-notes*

\marginpar[left]{right}				*\marginpar*
		This command creates a note in the margin. The first line will
		be at the same height as the line in the text where the
		|\marginpar| occurs.

		When you only specify the mandatory argument {right}, the text
		will be placed:
		* in the right margin for one-sided layout
		* in the outside margin for two-sided layout (|twoside|)
		* in the nearest margin for two-column layout (|twocolumn|)

\reversemarginpar				*\reversemarginpar*
		By issuing the command |\reversemarginpar|, you can force the
		marginal notes to go into the opposite (inside) margin.

When you specify both arguments, left is used for the left margin, and right
is used for the right margin.

The first word will normally not be hyphenated; you can enable hyphenation by
prefixing the first word with a \hspace{0pt} command (|hspace|).

==============================================================================
14. Math Formulae				*latex-math*
						*displaymath*
There are three environments (|latex-environments|) that put LaTeX in math
mode:
|math|  	For Formulae that appear right in the text.
|displaymath|  	For Formulae that appear on their own line.
|equation|  	The same as the displaymath environment except that it adds an
		equation number in the right margin.

The |math| environment can be used in both paragraph and LR mode, but the
|displaymath| and |equation| environments can be used only in paragraph mode. The
|math| and |displaymath| environments are used so often that they have the
following short forms:
	\(...\)    instead of    \begin{math}...\end{math}
	\[...\]    instead of    \begin{displaymath}...\end{displaymath}

In fact, the math environment is so common that it has an even shorter form:
	$ ... $    instead of     \(...\)

|sub-sup|	Also known as exponent or index.
|math-symbols|	Various mathematical squiggles.
|math-spacing|	Thick, medium, thin and negative spaces.
|math-misc|	Stuff that doesn't fit anywhere else.

==========
Subscripts & Superscripts			*sub-sup*
						*subscripts* *superscripts*

To get an expression exp to appear as a subscript, you just type _{exp}.  To
get exp to appear as a superscript, you type ^{exp}. LaTeX handles
superscripted superscripts and all of that stuff in the natural way. It even
does the right thing when something has both a subscript and a superscript.

==========
Math Symbols					*math-symbols*

LaTeX provides almost any mathematical symbol you're likely to need. The
commands for generating them can be used only in math mode. For example, if
you include >
	$\pi$
in your source, you will get the symbol in your output.

==========
Spacing in Math Mode				*math-spacing*

In a math environment, LaTeX ignores the spaces you type and puts in the
spacing that it thinks is best. LaTeX formats mathematics the way it's done in
mathematics texts. If you want different spacing, LaTeX provides the following
four commands for use in math mode:
	\; - a thick space			*math;*
	\: - a medium space			*math:*
	\, - a thin space			*math,*
	\! - a negative thin space		*math!*

==========
Math Miscellany					*math-misc*

\cdots						*\cdots*
		Produces a horizontal ellipsis where the dots are raised to
		the centre of the line.
\ddots						*\ddots*
		Produces a diagonal ellipsis.
\frac{num}{den}					*\frac*
		Produces the fraction num divided by den.
\ldots						*\ldots*
		Produces an ellipsis. This command works in any mode, not just
		math mode.
\overbrace{text}				*\overbrace*
		Generates a brace over text.
\overline{text}					*\overline*
		Causes the argument text to be overlined.
\sqrt[root]{arg}				*\sqrt*
		Produces the square root of its argument.  The optional
		argument, [root], determines what root to produce, i.e., the
		cube root of x+y would be typed as: >
			$\sqrt[3]{x+y}$.
\underbrace{text}				*\underbrace*
		Generates text with a brace underneath.
\underline{text}				*\underline*
		Causes the argument text to be underlined. This command can
		also be used in paragraph and LR mode.
\vdots						*\vdots*
		Produces a vertical ellipsis.

==============================================================================
15. Modes					*latex-modes*

When LaTeX is processing your input text, it is always in one of three modes:
	Paragraph mode					*paragraph-mode*
	Math mode					*math-mode*
	Left-to-right mode, called LR mode for short.	*lr-mode*

LaTeX changes mode only when it goes up or down a staircase to a different
level, though not all level changes produce mode changes. Mode changes occur
only when entering or leaving an environment, or when LaTeX is processing the
argument of certain text-producing commands.

|paragraph-mode| is the most common; it's the one LaTeX is in when processing
ordinary text. In that mode, LaTeX breaks your text into lines and breaks the
lines into pages. LaTeX is in |math-mode| when it's generating a mathematical
formula. In |lr-mode|, as in |paragraph-mode|, LaTeX considers the output that
it produces to be a string of words with spaces between them. However, unlike
|paragraph-mode|, LaTeX keeps going from left to right; it never starts a new
line in |lr-mode|. Even if you put a hundred words into an |\mbox|, LaTeX would
keep typesetting them from left to right inside a single box, and then
complain because the resulting box was too wide to fit on the line.

LaTeX is in |lr-mode| when it starts making a box with an |\mbox| command.  You
can get it to enter a different mode inside the box - for example, you can
make it enter |math-mode| to put a formula in the box. There are also several
text-producing commands and environments for making a box that put LaTeX in
|paragraph-mode|. The box make by one of these commands or environments will be
called a |\parbox|. When LaTeX is in |paragraph-mode| while making a box, it is
said to be in "inner paragraph mode". Its normal |paragraph-mode|, which it
starts out in, is called "outer paragraph mode".

==============================================================================
16. Page Styles					*latex-page-styles*

The |\documentclass| command determines the size and position of the page's head
and foot. The page style determines what goes in them.

|\maketitle| 	Generate a title page.
|\pagenumbering| Set the style used for page numbers.
|\pagestyle| 	Change the headings/footings style.
|\thispagestyle| Change the headings/footings style for this page.

\maketitle					*\maketitle*
		The |\maketitle| command generates a title on a separate title
		page - except in the |\article| class, where the title normally
		goes at the top of the first page.  Information used to
		produce the title is obtained from the following declarations:

		|\author|	Who wrote this stuff?
		|\date|		The date the document was created.
		|\thanks|	A special form of footnote.
		|\title|		How to set the document title.

		\author{names}				*\author* *\and*
			The |\author| command declares the author(s), where
			names is a list of authors separated by \and commands.
			Use |\\| to separate lines within a single author's
			entry -- for example, to give the author's institution
			or address.

		\date{text}				*\date*
			The |\date| command declares text to be the document's
			date.  With no |\date| command, the current date is
			used.

		\thanks{text}				*\thanks*
			The |\thanks| command produces a |\footnote| to the
			title.

		\title{text}				*\title*
			The |\title| command declares text to be the title. Use
			|\\| to tell LaTeX where to start a new line in a long
			title.

\pagenumbering{numstyle}			*\pagenumbering*
		Specifies the style of page numbers. Possible values of
		'numstyle' are:
			arabic - Arabic numerals		*arabic*
			roman  - Lowercase Roman numerals 	*roman*
			Roman  - Uppercase Roman numerals 	*Roman*
			alph   - Lowercase letters 		*alph*
			Alph   - Uppercase letters 		*Alph*

\pagestyle{option}				*\pagestyle*
						*plain* *empty* *headings*
		The |\pagestyle| command changes the style from the current
		page on throughout the remainder of your document.
		The valid options are:
		plain      - Just a plain page number.
		empty      - Produces empty heads and feet no page numbers.
		headings   - Puts running headings on each page. The document
			     style specifies what goes in the headings.
		myheadings - You specify what is to go in the heading with the
			     |\markboth| or the |\markright| commands.

		|\markboth| 	Set left and right headings.
		|\markright| 	Set right heading only.

		\markboth{left head}{right head}	*\markboth*
			The |\markboth| command is used in conjunction with the
			page style myheadings for setting both the left and
			the right heading.
			Note that a "left-hand heading" is generated by the
			last |\markboth| command before the end of the page,
			while a "right-hand heading" is generated by the first
			|\markboth| or |\markright| that comes on the page if
			there is one, otherwise by the last one before the
			page.


		\markright{right head}			*\markright*
			The |\markright| command is used in conjunction with
			the page style |\myheadings| for setting the right
			heading, leaving the left heading unchanged.
			Note that a "left-hand heading" is generated by the
			last |\markboth| command before the end of the page,
			while a "right-hand heading" is generated by the first
			|\markboth| or |\markright| that comes on the page if
			there is one, otherwise by the last one before the
			page.

\thispagestyle{option}				*\thispagestyle*
		The |\thispagestyle| command works in the same manner as the
		|\pagestyle| command except that it changes the style for the
		current page only.

==============================================================================
17. Sectioning					*latex-sectioning*

Sectioning commands provide the means to structure your text into units.
|\part|
|\chapter| (report and book class only)
|\section|
|\subsection|
|\subsubsection|
|\paragraph|
|\subparagraph|

All sectioning commands take the same general form, i.e.,

					*\part*
					*\chapter* (report and book class only)
					*\section* *\subsection* *\subsubsection*
					*\paragraph* *\subparagraph*
\chapter[optional]{title}
		In addition to providing the heading in the text, the
		mandatory argument of the sectioning command can appear in two
		other places:
		1. The table of contents
		2. The running head at the top of the page. You may not want
		   the same thing to appear in these other two places as
		   appears in the text heading. To handle this situation, the
		   sectioning commands have an optional argument that provides
		   the text for these other two purposes.

All sectioning commands have *\-forms that print a title, but do not include a
number and do not make an entry in the table of contents.

\appendix 					*\appendix*
		The |\appendix| command changes the way sectional units are
		numbered. The |\appendix| command generates no text and does
		not affect the numbering of parts. The normal use of this
		command is something like: >
			\chapter{The First Chapter}
			...
			\appendix \chapter{The First Appendix}


==============================================================================
18. Spaces & Boxes				*latex-spaces-boxes*

All the predefined length parameters See section Predefined lengths can be
used in the arguments of the box-making commands.

 Horizontal space:

|\dotfill|	Stretchable horizontal dots.
|\hfill|	Stretchable horizontal space.
|\hrulefill|	Stretchable horizontal rule.
|\hspace|	Fixed horizontal space.

 Vertical space:

|\addvspace|	Fixed vertical space.
|\bigskip|	Fixed vertical space.
|\medskip|	Fixed vertical space.
|\smallskip|	Fixed vertical space.
|\vfill|	Stretchable vertical space.
|\vspace|	Fixed vertical space.

 Boxes:

|\fbox|		Framebox.
|\framebox|	Framebox, adjustable position.
|\lrbox|	An environment like |\sbox|.
|\makebox|	Box, adjustable position.
|\mbox|		Box.
|\newsavebox|	Declare a name for saving a box.
|\parbox|	Box with text in paragraph mode.
|\raisebox|	Raise or lower text.
|\rule|		Lines and squares.
|\savebox|	Like |\makebox|, but save the text for later use.
|\sbox|		Like |\mbox|, but save the text for later use.
|\usebox|	Print saved text.

Horizontal space:				*latex-hor-space*

LaTeX removes horizontal space that comes at the end of a line. If you don't
want LaTeX to remove this space, include the optional * argument.  Then the
space is never removed.

\dotfill					*\dotfill*
		The |\dotfill| command produces a "rubber length" that produces
		dots instead of just spaces.

\hfill						*\hfill*
		The |\hfill| fill command produces a "rubber length" which can
		stretch or shrink horizontally. It will be filled with spaces.

\hrulefill					*\hrulefill*
		The |\hrulefill| fill command produces a "rubber length" which
		can stretch or shrink horizontally. It will be filled with a
		horizontal rule.

\hspace[*]{length}				*\hspace*
		The |\hspace| command adds horizontal space. The length of the
		space can be expressed in any terms that LaTeX understands,
		i.e., points, inches, etc. You can add negative as well as
		positive space with an |\hspace| command. Adding negative space
		is like backspacing.


Vertical space:					*latex-ver-space*

LaTeX removes vertical space that comes at the end of a page. If you don't
want LaTeX to remove this space, include the optional * argument.  Then the
space is never removed.

\addvspace{length}				*\addvspace*
		The |\addvspace| command normally adds a vertical space of
		height length.  However, if vertical space has already been
		added to the same point in the output by a previous
		|\addvspace| command, then this command will not add more space
		than needed to make the natural length of the total vertical
		space equal to length.

\bigskip					*\bigskip*
		The |\bigskip| command is equivalent to \vspace{bigskipamount}
		where bigskipamount is determined by the document class.

\medskip					*\medskip*
		The |\medskip| command is equivalent to \vspace{medskipamount}
		where medskipamount is determined by the document class.

\smallskip					*\smallskip*
		The |\smallskip| command is equivalent to
		\vspace{smallskipamount} where smallskipamount is determined
		by the document class.

\vfill						*\vfill*
		The |\vfill| fill command produces a rubber length which can
		stretch or shrink vertically.

\vspace[*]{length}				*\vspace*
		The |\vspace| command adds vertical space. The length of the
		space can be expressed in any terms that LaTeX understands,
		i.e., points, inches, etc. You can add negative as well as
		positive space with an |\vspace| command.


Boxes:						*latex-boxes*

\fbox{text}					*\fbox*
		The |\fbox| command is exactly the same as the |\mbox| command,
		except that it puts a frame around the outside of the box that
		it creates.

\framebox[width][position]{text}		*\framebox*
		The |\framebox| command is exactly the same as the |\makebox|
		command, except that it puts a frame around the outside of the
		box that it creates.
		The |\framebox| command produces a rule of thickness
		|\fboxrule|, and leaves a space |\fboxsep| between the rule and
		the contents of the box.

lrbox						*\lrbox*
\begin{lrbox}{cmd} text \end{lrbox}
		This is the environment form of |\sbox|.
		The text inside the environment is saved in the box cmd, which
		must have been declared with |\newsavebox|.

\makebox[width][position]{text} 		*\makebox*
		The |\makebox| command creates a box just wide enough to
		contain the text specified. The width of the box is specified
		by the optional [width] argument.  The position of the text
		within the box is determined by the optional [position]
		argument.
			c -- centred (default)
			l -- flushleft
			r -- flushright
			s -- stretch from left to right margin. The text must
			     contain stretchable space for this to work.
		See section |\picture-makebox|.

\mbox{text}					*\mbox*
		The |\mbox| command creates a box just wide enough to hold the
		text created by its argument.
		Use this command to prevent text from being split across
		lines.

\newsavebox{cmd}				*\newsavebox*
		Declares {cmd}, which must be a command name that is not
		already defined, to be a bin for saving boxes.


\parbox[position][height][innerpos]{width}{text} 	*\parbox*
		A parbox is a box whose contents are created in
		|\paragraph-mode|. The |\parbox| has two

	Mandatory arguments:
'width'		specifies the width of the parbox
'text'		the text that goes inside the parbox.

	Optional arguments:
'position'	LaTeX will position a parbox so its centre lines up with the
		centre of the text line. The optional position argument allows
		you to line up either the top or bottom line in the parbox
		(default is top).

'height'        If the height argument is not given, the box will have the
		natural height of the text.

'innerpos'	The inner-pos argument controls the placement of the text
		inside the box. If it is not specified, position is used.
			t -- text is placed at the top of the box
			c -- text is centred in the box
			b -- text is placed at the bottom of the box
			s -- stretch vertically. The text must contain
			     vertically stretchable space for this to work.

		A |\parbox| command is used for a parbox containing a small
		piece of text, with nothing fancy inside. In particular, you
		shouldn't use any of the paragraph-making environments inside
		a |\parbox| argument. For larger pieces of text, including ones
		containing a paragraph-making environment, you should use a
		|\minipage| environment.

\raisebox{distance}[extendabove][extendbelow]{text}   *\raisebox*
		The |\raisebox| command is used to raise or lower text. The
		first mandatory argument specifies how high the text is to be
		raised (or lowered if it is a negative amount). The text
		itself is processed in LR mode.
		Sometimes it's useful to make LaTeX think something has a
		different size than it really does - or a different size than
		LaTeX would normally think it has.  The |\raisebox| command
		lets you tell LaTeX how tall it is.
		The first optional argument, extend-above, makes LaTeX think
		that the text extends above the line by the amount specified.
		The second optional argument, extend-below, makes LaTeX think
		that the text extends below the line by the amount specified.

\rule[raiseheight]{width}{thickness} 		*\rule*
		The |\rule| command is used to produce horizontal lines. The
		arguments are defined as follows:
'raiseheight'	specifies how high to raise the rule (optional)
'width'		specifies the length of the rule (mandatory)
'thickness'	specifies the thickness of the rule (mandatory)

\savebox{cmd}[width][pos]{text} 		*\savebox*
		This command typeset text in a box just as for |\makebox|.
		However, instead of printing the resulting box, it saves it in
		bin cmd, which must have been declared with |\newsavebox|.

\sbox{text}					*\sbox*
		This commands typeset text in a box just as for |\mbox|.
		However, instead of printing the resulting box, it saves it in
		bin cmd, which must have been declared with |\newsavebox|.

\usebox{cmd}					*\usebox*
		Prints the box most recently saved in bin cmd by a |\savebox|
		command.

==============================================================================
19. Special Characters				*latex-special*

The following characters play a special role in LaTeX and are called "special
printing characters", or simply "special characters". >
			 #  $  %  &  ~  _  ^  \  {  }
Whenever you put one of these special characters into your file, you are doing
something special. If you simply want the character to be printed just as any
other letter, include a \ in front of the character. For example, \$ will
produce $ in your output.

One exception to this rule is the \ itself because |\\| has its own special
meaning. A \ is produced by typing $\backslash$ in your file.

Also, \~ means `place a tilde accent over the following letter', so you will
probably want to use |\verb| instead.
						*\symbol*
In addition, you can access any character of a font once you know its number
by using the |\symbol| command. For example, the character used for displaying
spaces in the |\verb|* command has the code decimal 32, so it can be typed as
\symbol{32}.

You can also specify octal numbers with ' or hexadecimal numbers with ", so
the previous example could also be written as \symbol{'40} or \symbol{"20}.

==============================================================================
20. Splitting the Input				*latex-inputting*

A large document requires a lot of input. Rather than putting the whole input
in a single large file, it's more efficient to split it into several smaller
ones. Regardless of how many separate files you use, there is one that is the
root file; it is the one whose name you type when you run LaTeX.

|\include| 		Conditionally include a file
|\includeonly| 		Determine which files are included
|\input| 		Unconditionally include a file

\include{file}					*\include*
		The \include command is used in conjunction with the
		|\includeonly| command for selective inclusion of
		files. The file argument is the first name of a file,
		denoting `file.tex' . If file is one the file names in
		the file list of the |\includeonly| command or if there
		is no |\includeonly| command, the \include command is
		equivalent to: >
			\clearpage \input{file} \clearpage
<
		except that if the file `file.tex' does not exist,
		then a warning message rather than an error is
		produced. If the file is not in the file list, the
		\include command is equivalent to |\clearpage|.

		The |\include| command may not appear in the preamble or in a
		file read by another |\include| command.

\includeonly{filelist}	 			*\includeonly*
		The |\includeonly| command controls which files will be read in
		by an |\include| command. {filelist} should be a
		comma-separated list of filenames. Each filename must match
		exactly a filename specified in a |\include| command. This
		command can only appear in the preamble.

\input{file} 					*\input*
		The |\input| command causes the indicated file to be read and
		processed, exactly as if its contents had been inserted in the
		current file at that point. The file name may be a complete
		file name with extension or just a first name, in which case
		the file `file.tex' is used.
==============================================================================
21. Starting & Ending				*latex-start-end*

Your input file must contain the following commands as a minimum:
\documentclass{class} 		|\documentclass|
\begin{document} 		|\begin|
... your text goes here ...
\end{document} 			|\end|

where the class selected is one of the valid classes for LaTeX.
See |\classes|for details of the various document classes.

You may include other LaTeX commands between the |\documentclass| and the
\begin{document} commands (i.e., in the `preamble').
==============================================================================
22. Table of Contents				*latex-toc*

						*\tableofcontents*
A table of contents is produced with the |\tableofcontents| command. You put
the command right where you want the table of contents to go; LaTeX does the
rest for you. It produces a heading, but it does not automatically start a new
page. If you want a new page after the table of contents, include a |\newpage|
command after the |\tableofcontents| command.

						*\listoffigures* *\listoftables*
There are similar commands |\listoffigures| and |\listoftables| for producing a
list of figures and a list of tables, respectively.  Everything works exactly
the same as for the table of contents.

						*\nofiles*
NOTE: If you want any of these items to be generated, you cannot have the
\nofiles command in your document.

|\addcontentsline|	Add an entry to table of contents etc.
|\addtocontents|		Add text directly to table of contents file etc.

\addcontentsline{file}{secunit}{entry}		*\addcontentsline*
		The |\addcontentsline| command adds an entry to the specified
		list or table where:
{file}		is the extension of the file on which information is to be
        	written:
        		toc (table of contents),
        		lof (list of figures),
        		lot (list of tables).
{secunit}	controls the formatting of the entry. It should be one of the
		following, depending upon the value of the file argument:
			toc -- the name of the sectional unit, such as part or
				subsection.
			lof -- figure
			lot -- table
{entry}		is the text of the entry.

\addtocontents{file}{text}				*\addtocontents*
		The |\addtocontents| command adds text (or formatting commands)
		directly to the file that generates the table of contents or
		list of figures or tables.
{file}		is the extension of the file on which information is to be written:
			toc (table of contents),
			lof (list of figures),
			lot (list of tables).
{text}		is the information to be written.

==============================================================================
23. Terminal Input/Output				*latex-terminal*

|\typein|		Read text from the terminal.
|\typeout|		Write text to the terminal.

\typein[cmd]{msg}					*\typein*
		Prints {msg} on the terminal and causes LaTeX to stop and wait
		for you to type a line of input, ending with return. If the
		[cmd] argument is missing, the typed input is processed as if
		it had been included in the input file in place of the
		|\typein| command. If the [cmd] argument is present, it must be
		a command name. This command name is then defined or redefined
		to be the typed input.

\typeout{msg}						*\typeout*
		Prints {msg} on the terminal and in the `.log' file. Commands
		in {msg} that are defined with |\newcommand| or |\renewcommand|
		are replaced by their definitions before being printed.

							*\space*
LaTeX's usual rules for treating multiple spaces as a single space and
ignoring spaces after a command name apply to {msg}. A |\space| command in {msg}
causes a single space to be printed. A ^^J in {msg} prints a newline.

==============================================================================
24. Typefaces					*latex-typefaces*

The typeface is specified by giving the "size" and "style". A typeface is also
called a "font".
|font-styles|		Select roman, italics etc.
|font-size|		Select point size.
|font-lowlevelcommands|	Commands for wizards.

Styles						*font-styles*

The following type style commands are supported by LaTeX.

These commands are used like: >
	\textit{italics text}.
The corresponding command in parenthesis is the "declaration form", which
takes no arguments. The scope of the declaration form lasts until the next
type style command or the end of the current group.

The declaration forms are cumulative; i.e., you can say: >
	\sffamily\bfseries
to get sans serif boldface.

You can also use the environment form of the declaration forms; e.g.: >
	\begin{ttfamily}...\end{ttfamily}.
<
\textrm (\rmfamily)		*\textrm* *\rmfamily*
		Roman

\textit (\itshape)		*\textit* *\itshape* *\emph*
		Emphasis (toggles between |\textit| and |\textrm|).

\textmd (\mdseries)		*\textmd* *\mdseries*
		Medium weight (default). The opposite of boldface.

\textbf (\bfseries)		*\textbf* *\bfseries*
		Boldface.

\textup (\upshape)		*\textup* *\upshape*
		Upright (default).  The opposite of slanted.

\textsl (\slshape)		*\textsl* *\slshape*
		Slanted.

\textsf (\sffamily)		*\textsf* *\sffamily*
		Sans serif.

\textsc (\scshape)		*\textsc* *\scshape*
		Small caps.

\texttt (\ttfamily)		*\texttt* *\ttfamily*
		Typewriter.

\textnormal (\normalfont)	*\textnormal* *\normalfont*
		Main document font.

\mathrm				*\mathrm*
		Roman, for use in math mode.

\mathbf  			*\mathbf*
		Boldface, for use in math mode.

\mathsf				*\mathsf*
		Sans serif, for use in math mode.

\mathtt				*\mathtt*
		Typewriter, for use in math mode.

\mathit				*\mathit*
		Italics, for use in math mode, e.g. variable names with
		several letters.

\mathnormal			*\mathnormal*
		For use in math mode, e.g. inside another type style
		declaration.

\mathcal			*\mathcal*
 `Calligraphic' letters, for use in math mode.

				*\mathversion*
In addition, the command \mathversion{bold} can be used for switching to bold
letters and symbols in formulas. \mathversion{normal} restores the default.

==========
Sizes						*font-size*

The following standard type size commands are supported by LaTeX.

The commands as listed here are "declaration forms". The scope of the
declaration form lasts until the next type style command or the end of the
current group.

You can also use the environment form of these commands; e.g. >
	\begin{tiny}...\end{tiny}

\tiny			        *\tiny*
\scriptsize		        *\scriptsize*
\footnotesize		        *\footnotesize*
\small			        *\small*
\normalsize(default)	        *\normalsize*
\large			        *\large*
\Large			        *\Large*
\LARGE			        *\LARGE*
\huge			        *\huge*
\Huge			        *\Huge*

==========
Low-level font commands				*font-lowlevelcommands*

These commands are primarily intended for writers of macros and packages. The
commands listed here are only a subset of the available ones. For full
details, you should consult Chapter 7 of The LaTeX Companion.

\fontencoding{enc}				*\fontencoding*
		Select font encoding. Valid encodings include OT1 and T1.

\fontfamily{family}  				*\fontfamily*
		Select font family. Valid families include:
			cmr  for Computer Modern Roman
			cmss for Computer Modern Sans Serif
			cmtt for Computer Modern Typewriter
		and numerous others.

\fontseries{series}				*\fontseries*
		Select font series. Valid series include:
			m Medium (normal)
			b Bold
			c Condensed
			bc Bold condensed
			bx Bold extended
		and various other combinations.

\fontshape{shape}				*\fontshape*
		Select font shape. Valid shapes are:
			n Upright (normal)
			it Italic
			sl Slanted (oblique)
			sc Small caps
			ui Upright italics
			ol Outline
		The two last shapes are not available for most font families.

\fontsize{size}{skip}				*\fontsize*
		Set font size. The first parameter is the font size to switch
		to; the second is the \baselineskip to use. The unit of both
		parameters defaults to pt. A rule of thumb is that the
		baselineskip should be 1.2 times the font size.

\selectfont					*\selectfont*
		The changes made by calling the four font commands described
		above do not come into effect until |\selectfont| is called.

\usefont{enc}{family}{series}{shape}		*\usefont*
		Equivalent to calling |\fontencoding|, |\fontfamily|,
		|\fontseries| and |\fontshape| with the given parameters,
		followed by |\selectfont|.

==============================================================================
25. Parameters					*latex-parameters*

The input file specification indicates the file to be formatted; TeX uses
`.tex' as a default file extension. If you omit the input file entirely, TeX
accepts input from the terminal. You specify command options by supplying a
string as a parameter to the command; e.g. >

	latex "\scrollmode\input foo.tex"

will process `foo.tex' without pausing after every error.

Output files are always created in the current directory. When you fail to
specify an input file name, TeX bases the output names on the file
specification associated with the logical name TEX_OUTPUT, typically
texput.log.

 vim:tw=78:ts=8:ft=help:norl:
ftplugin/ATP_files/LatexBox_common.vim	[[[1
302
" Author:	   David Munger (latexbox vim plugin)
" Description: LaTeX Box common functions
" Maintainer:  Marcin Szamotulski
" Note:		   This file is a part of Automatic Tex Plugin for Vim.
" Language:    tex
" Last Change: Mon Oct 31, 2011 at 23:38:53  +0000

let s:sourced = exists("s:sourced") ? 1 : 0
" Settings {{{

" Compilation {{{

" g:vim_program {{{
if !exists('g:vim_program')

	if match(&shell, '/bash$') >= 0
		let ppid = '$PPID'
	else
		let ppid = '$$'
	endif

	" attempt autodetection of vim executable
	let g:vim_program = ''
	let tmpfile = tempname()
	silent execute '!ps -o command= -p ' . ppid . ' > ' . tmpfile
	for line in readfile(tmpfile)
		let line = matchstr(line, '^\S\+\>')
		if !empty(line) && executable(line)
			let g:vim_program = line . ' -g'
			break
		endif
	endfor
	call delete(tmpfile)

	if empty(g:vim_program)
		if has('gui_macvim')
			let g:vim_program = '/Applications/MacVim.app/Contents/MacOS/Vim -g'
		else
			let g:vim_program = v:progname
		endif
	endif
endif
" }}}

if !exists('g:LatexBox_latexmk_options')
	let g:LatexBox_latexmk_options = ''
endif
if !exists('g:LatexBox_output_type')
	let g:LatexBox_output_type = 'pdf'
endif
if !exists('g:LatexBox_viewer')
	let g:LatexBox_viewer = b:atp_Viewer
endif
if !exists('g:LatexBox_autojump')
	let g:LatexBox_autojump = 0
endif
" }}}

" Completion {{{
if !exists('g:LatexBox_completion_close_braces')
	let g:LatexBox_completion_close_braces = 1
endif
if !exists('g:LatexBox_bibtex_wild_spaces')
	let g:LatexBox_bibtex_wild_spaces = 1
endif

if !exists('g:LatexBox_cite_pattern')
	let g:LatexBox_cite_pattern = '\C\\cite\(p\|t\)\=\*\=\(\[[^\]]*\]\)*\_\s*{'
endif
if !exists('g:LatexBox_ref_pattern')
	let g:LatexBox_ref_pattern = '\C\\v\?\(eq\|page\)\?ref\*\?\_\s*{'
endif

if !exists('g:LatexBox_completion_environments')
	let g:LatexBox_completion_environments = [
		\ {'word': 'itemize',		'menu': 'bullet list' },
		\ {'word': 'enumerate',		'menu': 'numbered list' },
		\ {'word': 'description',	'menu': 'description' },
		\ {'word': 'center',		'menu': 'centered text' },
		\ {'word': 'figure',		'menu': 'floating figure' },
		\ {'word': 'table',			'menu': 'floating table' },
		\ {'word': 'equation',		'menu': 'equation (numbered)' },
		\ {'word': 'align',			'menu': 'aligned equations (numbered)' },
		\ {'word': 'align*',		'menu': 'aligned equations' },
		\ {'word': 'document' },
		\ {'word': 'abstract' },
		\ ]
endif

if !exists('g:LatexBox_completion_commands')
	let g:LatexBox_completion_commands = [
		\ {'word': '\begin{' },
		\ {'word': '\end{' },
		\ {'word': '\item' },
		\ {'word': '\label{' },
		\ {'word': '\ref{' },
		\ {'word': '\eqref{eq:' },
		\ {'word': '\cite{' },
		\ {'word': '\chapter{' },
		\ {'word': '\section{' },
		\ {'word': '\subsection{' },
		\ {'word': '\subsubsection{' },
		\ {'word': '\paragraph{' },
		\ {'word': '\nonumber' },
		\ {'word': '\bibliography' },
		\ {'word': '\bibliographystyle' },
		\ ]
endif
" }}}

" Vim Windows {{{
if !exists('g:LatexBox_split_width')
	let g:LatexBox_split_width = 30
endif
" }}}
" }}}

" Filename utilities {{{
"
function! LatexBox_GetMainTexFile()
	return atplib#FullPath(b:atp_MainFile)
endfunction

" Return the directory of the main tex file
function! LatexBox_GetTexRoot()
	return fnamemodify(atplib#FullPath(b:atp_MainFile), ':h')
endfunction

function! LatexBox_GetTexBasename(with_dir)
	if a:with_dir
		return fnamemodify(atplib#FullPath(b:atp_MainFile), ':r') 
	else
		return fnamemodify(b:atp_MainFile, ':t:r')
	endif
endfunction

function! LatexBox_GetAuxFile()
	return LatexBox_GetTexBasename(1) . '.aux'
endfunction

function! LatexBox_GetLogFile()
	return LatexBox_GetTexBasename(1) . '.log'
endfunction

function! LatexBox_GetOutputFile()
	return LatexBox_GetTexBasename(1) . '.' . g:LatexBox_output_type
endfunction
" }}}

" View Output {{{
" function! LatexBox_View()
" 	let outfile = LatexBox_GetOutputFile()
" 	if !filereadable(outfile)
" 		echomsg "[ATP:] ".fnamemodify(outfile, ':.') . ' is not readable'
" 		return
" 	endif
" 	let cmd = '!' . g:LatexBox_viewer . ' ' . shellescape(outfile) . ' &>/dev/null &'
" 	if has("gui_running")
" 		silent execute cmd
" 	else
" 		execute cmd
" 	endif
" endfunction
" 
" command! LatexView			call LatexBox_View()
" }}}

" In Comment {{{
" LatexBox_InComment([line], [col])
" return true if inside comment
function! LatexBox_InComment(...)
	let line	= a:0 >= 1 ? a:1 : line('.')
	let col		= a:0 >= 2 ? a:2 : col('.')
	return synIDattr(synID(line("."), col("."), 0), "name") =~# '^texComment'
endfunction
" }}}

" Get Current Environment {{{
" LatexBox_GetCurrentEnvironment([with_pos])
" Returns:
" - environment													if with_pos is not given
" - [envirnoment, lnum_begin, cnum_begin, lnum_end, cnum_end]	if with_pos is nonzero
function! LatexBox_GetCurrentEnvironment(...)

	if a:0 > 0
		let with_pos = a:1
	else
		let with_pos = 0
	endif

	if atplib#complete#CheckSyntaxGroups(['texMathZoneV'])
	    let begin_pat 	= '\\\@<!\\('
	    let end_pat		= '\\\@<!\\)'
	elseif atplib#complete#CheckSyntaxGroups(['texMathZoneW'])
	    let begin_pat 	= '\\\@<!\\\['
	    let end_pat		= '\\\@<!\\\]'
	else
	    let begin_pat = '\C\\begin\_\s*{[^}]*}'
	    let end_pat = '\C\\end\_\s*{[^}]*}'
	endif
	let saved_pos = getpos('.')

	" move to the left until on a backslash
	" getpos(".") in visual mode returns getpos("'<") this makes a problem
	" here, simple change of mode here doesn't help, because mode() returns
	" 'n' here.  
	let [bufnum, lnum, cnum, off] = getpos('.')
	let line = getline(lnum)
	while cnum > 1 && line[cnum - 1] != '\'
		let cnum -= 1
	endwhile
	call cursor(lnum, cnum)

	" match begin/end pairs but skip comments
	let flags = 'bnW'
	if strpart(getline('.'), col('.') - 1) =~ '^\%(' . begin_pat . '\)'
		let flags .= 'c'
	endif
	let [lnum1, cnum1] = searchpairpos(begin_pat, '', end_pat, flags, 'LatexBox_InComment()')

	let env = ''

	if lnum1

		let line = strpart(getline(lnum1), cnum1 - 1)

		if empty(env)
			let env = matchstr(line, '^\C\\begin\_\s*{\zs[^}]*\ze}')
		endif
		if empty(env)
			let env = matchstr(line, '^\\\[')
		endif
		if empty(env)
			let env = matchstr(line, '^\\(')
		endif

	endif

	if with_pos == 1

		let flags = 'nW'
		if !(lnum1 == lnum && cnum1 == cnum)
			let flags .= 'c'
		endif

		let [lnum2, cnum2] = searchpairpos(begin_pat, '', end_pat, flags, 'LatexBox_InComment()')
		call setpos('.', saved_pos)
		return [env, lnum1, cnum1, lnum2, cnum2]
	else
		call setpos('.', saved_pos)
		return env
	endif


endfunction
" }}}


" Tex To Tree {{{
" stores nested braces in a tree structure
function! LatexBox_TexToTree(str)
	let tree = []
	let i1 = 0
	let i2 = -1
	let depth = 0
	while i2 < len(a:str)
		let i2 = match(a:str, '[{}]', i2 + 1)
		if i2 < 0
			let i2 = len(a:str)
		endif
		if i2 >= len(a:str) || a:str[i2] == '{'
			if depth == 0 
				let item = substitute(strpart(a:str, i1, i2 - i1), '^\s*\|\s*$', '', 'g')
				if !empty(item)
					call add(tree, item)
				endif
				let i1 = i2 + 1
			endif
			let depth += 1
		else
			let depth -= 1
			if depth == 0
				call add(tree, LatexBox_TexToTree(strpart(a:str, i1, i2 - i1)))
				let i1 = i2 + 1
			endif
		endif
	endwhile
	return tree
endfunction
" }}}

" Tree To Tex {{{
function! LatexBox_TreeToTex(tree)
	if type(a:tree) == type('')
		return a:tree
	else
		return '{' . join(map(a:tree, 'LatexBox_TreeToTex(v:val)'), '') . '}'
	endif
endfunction
" }}}

" vim:fdm=marker:ff=unix:noet:ts=4:sw=4
ftplugin/ATP_files/LatexBox_complete.vim	[[[1
203
" Author:	David Mnuger (latexbox vim plugin)
" Maintainer:	Marcin Szamotulski
" Note:		This file is a part of Automatic Tex Plugin for Vim.
" Email:	mszamot [AT] gmail [DOT] com
" Language:	tex
" Last Change:

let s:sourced = exists("s:sourced") ? 1 : 0
if s:sourced && !g:atp_reload_functions
    finish
endif

if get(split(globpath(b:atp_ProjectDir, fnamemodify(b:atp_MainFile, ":t")), "\n"), 0, '') != ''
    let s:atp_MainFile	= ( g:atp_RelativePath ? split(globpath(b:atp_ProjectDir, fnamemodify(b:atp_MainFile, ":t")), "\n")[0] : b:atp_MainFile )
else
    let s:atp_MainFile	= atplib#FullPath(b:atp_MainFile)
endif

" latex-box/complete.vim
" <SID> Wrap {{{
function! s:GetSID()
	return matchstr(expand('<sfile>'), '\zs<SNR>\d\+_\ze.*$')
endfunction
let s:SID = s:GetSID()
" a:1 is the file where the function is defined. 
function! s:SIDWrap(func,...)
	return s:SID . a:func
endfunction
" }}}

" BibTeX search {{{

" find the \bibliography{...} commands
" the optional argument is the file name to be searched
function! LatexBox_kpsewhich(file)
	let old_dir = getcwd()
	execute 'lcd ' . fnameescape(LatexBox_GetTexRoot())
	redir => out
	silent execute '!kpsewhich ' . a:file
	redir END

	let out = split(out, "\<NL>")[-1]
	let out = substitute(out, '\r', '', 'g')
	let out = glob(fnamemodify(out, ':p'), 1)
	
	execute 'lcd ' . fnameescape(old_dir)

	return out
endfunction

function! s:FindBibData(...)

	if a:0 == 0
		let file = ( g:atp_RelativePath ? split(globpath(b:atp_ProjectDir, fnamemodify(b:atp_MainFile, ":t")), "\n")[0] : b:atp_MainFile )
	else
		let file = a:1
	endif

	if empty(glob(file, 1))
		return ''
		endif

	let lines = readfile(file)

	let bibdata_list = []

	let bibdata_list +=
				\ map(filter(copy(lines), 'v:val =~ ''\C\\bibliography\s*{[^}]\+}'''),
				\ 'matchstr(v:val, ''\C\\bibliography\s*{\zs[^}]\+\ze}'')')

	let bibdata_list +=
				\ map(filter(copy(lines), 'v:val =~ ''\C\\\%(input\|include\)\s*{[^}]\+}'''),
				\ 's:FindBibData(LatexBox_kpsewhich(matchstr(v:val, ''\C\\\%(input\|include\)\s*{\zs[^}]\+\ze}'')))')

	let bibdata_list +=
				\ map(filter(copy(lines), 'v:val =~ ''\C\\\%(input\|include\)\s\+\S\+'''),
				\ 's:FindBibData(LatexBox_kpsewhich(matchstr(v:val, ''\C\\\%(input\|include\)\s\+\zs\S\+\ze'')))')

	let bibdata = join(bibdata_list, ',')

	return bibdata
endfunction

let s:bstfile = expand('<sfile>:p:h') . '/vimcomplete'

function! LatexBox_BibSearch(regexp)

	" find bib data
    let bibdata = s:FindBibData()
    if bibdata == ''
	echomsg '[ATP:] error: no \bibliography{...} command found'
	return
    endif

    " write temporary aux file
    let tmpbase = b:atp_ProjectDir  . '/_LatexBox_BibComplete'
    let auxfile = tmpbase . '.aux'
    let bblfile = tmpbase . '.bbl'
    let blgfile = tmpbase . '.blg'

    call writefile(['\citation{*}', '\bibstyle{' . s:bstfile . '}', '\bibdata{' . bibdata . '}'], auxfile)

    let atp_MainFile	= atplib#FullPath(b:atp_MainFile)
    silent execute '! cd ' shellescape(fnamemodify(atp_MainFile,":h")) .
				\ ' ; bibtex -terse ' . fnamemodify(auxfile, ':t') . ' >/dev/null'

    let res = []
    let curentry = ''

	let lines = split(substitute(join(readfile(bblfile), "\n"), '\n\n\@!\(\s\=\)\s*\|{\|}', '\1', 'g'), "\n")
			
    for line in filter(lines, 'v:val =~ a:regexp')
		let matches = matchlist(line, '^\(.*\)||\(.*\)||\(.*\)||\(.*\)||\(.*\)')
            if !empty(matches) && !empty(matches[1])
                call add(res, {'key': matches[1], 'type': matches[2],
							\ 'author': matches[3], 'year': matches[4], 'title': matches[5]})
	    endif
    endfor

	call delete(auxfile)
	call delete(bblfile)
	call delete(blgfile)

	return res
endfunction
" }}}

" Change Environment {{{
function! s:ChangeEnvPrompt()

	let [env, lnum, cnum, lnum2, cnum2] = LatexBox_GetCurrentEnvironment(1)

	let new_env = input('change ' . env . ' for: ', '', 'customlist,' . s:SIDWrap('GetEnvironmentList'))
	if empty(new_env)
		return
	endif

	if new_env == '\[' || new_env == '['
		let begin = '\['
		let end = '\]'
	elseif new_env == '\(' || new_env == '('
		let begin = '\('
		let end = '\)'
	else
		let l:begin = '\begin{' . new_env . '}'
		let l:end = '\end{' . new_env . '}'
	endif
	
	if env == '\[' || env == '\('
		let line = getline(lnum2)
		let line = strpart(line, 0, cnum2 - 1) . l:end . strpart(line, cnum2 + 1)
		call setline(lnum2, line)

		let line = getline(lnum)
		let line = strpart(line, 0, cnum - 1) . l:begin . strpart(line, cnum + 1)
		call setline(lnum, line)
	else
		let line = getline(lnum2)
		let line = strpart(line, 0, cnum2 - 1) . l:end . strpart(line, cnum2 + len(env) + 5)
		call setline(lnum2, line)

		let line = getline(lnum)
		let line = strpart(line, 0, cnum - 1) . l:begin . strpart(line, cnum + len(env) + 7)
		call setline(lnum, line)
	endif

endfunction

function! s:GetEnvironmentList(lead, cmdline, pos)
	let suggestions = []
	
	if !exists("b:atp_LocalEnvironments")
	    call LocalCommands(0)
	elseif has("python")
	    call LocalCommands(0)
	endif
	let l:completion_list=atplib#Extend(g:atp_Environments,b:atp_LocalEnvironments)

	for entry in l:completion_list
" 		let env = entry.word
		if entry =~ '^' . a:lead
			call add(suggestions, entry)
		endif
	endfor

	if len(suggestions) > 5
	    call sort(suggestions)
	endif

	return suggestions
endfunction
" }}}

" Next Charaters Match {{{
function! s:NextCharsMatch(regex)
	let rest_of_line = strpart(getline('.'), col('.') - 1)
	return rest_of_line =~ a:regex
endfunction
" }}}

" Mappings {{{
nmap <silent> <Plug>LatexChangeEnv			:call <SID>ChangeEnvPrompt()<CR>
" }}}
ftplugin/ATP_files/LatexBox_latexmk.vim	[[[1
231
" Author: 		David Munger (mungerd@gmail.com)
" Maintainer:	Marcin Szamotulski
" Note:			This file is a part of Automatic Tex Plugin for Vim.
" Language:		tex
" Last Change:

let s:sourced	 		= exists("s:sourced") ? 1 : 0

if !s:sourced || g:atp_reload_functions
" <SID> Wrap {{{
function! s:GetSID()
	return matchstr(expand('<sfile>'), '\zs<SNR>\d\+_\ze.*$')
endfunction
let s:SID = s:GetSID()
function! s:SIDWrap(func)
	return s:SID . a:func
endfunction
" }}}


" dictionary of latexmk PID's (basename: pid)
let s:latexmk_running_pids = {}

" Set PID {{{
function! s:LatexmkSetPID(basename, pid)
	let s:latexmk_running_pids[a:basename] = a:pid
endfunction
" }}}

" Callback {{{
function! s:LatexmkCallback(basename, status)
	"let pos = getpos('.')
	if a:status
		echomsg "[LatexBox:] latexmk exited with status " . a:status
	else
		echomsg "[LatexBox:] latexmk finished"
	endif
	call remove(s:latexmk_running_pids, a:basename)
	call LatexBox_LatexErrors(g:LatexBox_autojump && a:status, a:basename)
	"call setpos('.', pos)
endfunction
" }}}

" Latexmk {{{
function! LatexBox_Latexmk(force)

	if empty(v:servername)
		echoerr "cannot run latexmk in background without a VIM server"
		return
	endif

	let basename = LatexBox_GetTexBasename(1)

	if has_key(s:latexmk_running_pids, basename)
		echomsg "[LatexBox:] latexmk is already running for `" . fnamemodify(basename, ':t') . "'"
		return
	endif

	let callsetpid = s:SIDWrap('LatexmkSetPID')
	let callback = s:SIDWrap('LatexmkCallback')

	let l:options = '-' . g:LatexBox_output_type . ' -quiet ' . g:LatexBox_latexmk_options
	if a:force
		let l:options .= ' -g'
	endif
	let l:options .= " -e '$pdflatex =~ s/ / -file-line-error /'"
	let l:options .= " -e '$latex =~ s/ / -file-line-error /'"

	" callback to set the pid
	let vimsetpid = g:vim_program . ' --servername ' . v:servername . ' --remote-expr ' .
				\ shellescape(callsetpid) . '\(\"' . fnameescape(basename) . '\",$$\)'

	" wrap width in log file
	let max_print_line = 2000

	" set environment
	if match(&shell, '/tcsh$') >= 0
		let l:env = 'setenv max_print_line ' . max_print_line . '; '
	else
		let l:env = 'max_print_line=' . max_print_line
	endif

	let pwd = getcwd()
	exe "lcd ". fnameescape(b:atp_ProjectDir)

	" latexmk command
	let cmd =  l:env .
				\ ' latexmk ' . l:options	. ' ' . shellescape(b:atp_MainFile)

	" callback after latexmk is finished
	let vimcmd = g:vim_program . ' --servername ' . v:servername . ' --remote-expr ' . 
				\ shellescape(callback) . '\(\"' . fnameescape(basename) . '\",$?\)'

	silent execute '! ( ' . vimsetpid . ' ; ( ' . cmd . ' ) ; ' . vimcmd . ' ) >&/dev/null &'
	exe "lcd ".fnameescape(pwd)
	if !has("gui_running")
		redraw!
	endif
endfunction
" }}}

" LatexmkStop {{{
function! LatexBox_LatexmkStop()

	let basename = LatexBox_GetTexBasename(1)

	if !has_key(s:latexmk_running_pids, basename)
		echomsg "[LatexBox:] latexmk is not running for `" . fnamemodify(basename, ':t') . "'"
		return
	endif

	call s:kill_latexmk(s:latexmk_running_pids[basename])

	call remove(s:latexmk_running_pids, basename)
	echomsg "[LatexBox:] latexmk stopped for `" . fnamemodify(basename, ':t') . "'"
endfunction
" }}}

" kill_latexmk {{{
function! s:kill_latexmk(gpid)

	" This version doesn't work on systems on which pkill is not installed:
	"!silent execute '! pkill -g ' . pid

	" This version is more portable, but still doesn't work on Mac OS X:
	"!silent execute '! kill `ps -o pid= -g ' . pid . '`'

	" Since 'ps' behaves differently on different platforms, we must use brute force:
	" - list all processes in a temporary file
	" - match by process group ID
	" - kill matches
	let pids = []
	let tmpfile = tempname()
	silent execute '!ps x -o pgid,pid > ' . tmpfile
	for line in readfile(tmpfile)
		let pid = matchstr(line, '^\s*' . a:gpid . '\s\+\zs\d\+\ze')
		if !empty(pid)
			call add(pids, pid)
		endif
	endfor
	call delete(tmpfile)
	if !empty(pids)
		call atplib#KillPIDs(pids)
	endif
endfunction
" }}}

" kill_all_latexmk {{{
function! s:kill_all_latexmk()
	for gpid in values(s:latexmk_running_pids)
		call s:kill_latexmk(gpid)
	endfor
	let s:latexmk_running_pids = {}
endfunction
" }}}

" LatexmkClean {{{
function! LatexBox_LatexmkClean(cleanall) 
	if a:cleanall
		let l:options = '-C'
	else
		let l:options = '-c'
	endif

	silent execute '! cd ' . shellescape(LatexBox_GetTexRoot()) . ' ; latexmk ' . l:options
				\	. ' ' . shellescape(LatexBox_GetMainTexFile()) . ' >&/dev/null'
	if !has("gui_running")
		redraw!
	endif

	echomsg "[LatexBox:] latexmk clean finished"

endfunction
" }}}

" LatexmkStatus {{{
function! LatexBox_LatexmkStatus(detailed)

	if a:detailed
		if empty(s:latexmk_running_pids)
			echo "latexmk is not running"
		else
			let plist = ""
			for [basename, pid] in items(s:latexmk_running_pids)
				if !empty(plist)
					let plist .= '; '
				endif
				let plist .= fnamemodify(basename, ':t') . ':' . pid
			endfor
			echo "latexmk is running (" . plist . ")"
		endif
	else
		let basename = LatexBox_GetTexBasename(1)
		if has_key(s:latexmk_running_pids, basename)
			echo "latexmk is running"
		else
			echo "latexmk is not running"
		endif
	endif

endfunction
" }}}

" LatexErrors {{{
" LatexBox_LatexErrors(jump, [basename])
function! LatexBox_LatexErrors(jump, ...)
	if a:0 >= 1
		let log = a:1 . '.log'
	else
		let log = LatexBox_GetLogFile()
	endif

	if (a:jump)
		execute 'cfile ' . fnameescape(log)
	else
		execute 'cgetfile ' . fnameescape(log)
	endif
endfunction
" }}}
endif

" Commands {{{
command! -buffer -bang Latexmk				call LatexBox_Latexmk(<q-bang> == "!")
command! -buffer -bang LatexmkClean			call LatexBox_LatexmkClean(<q-bang> == "!")
command! -buffer -bang LatexmkStatus		call LatexBox_LatexmkStatus(<q-bang> == "!")
command! -buffer LatexmkStop				call LatexBox_LatexmkStop()
" }}}

autocmd VimLeavePre * call <SID>kill_all_latexmk()

" vim:fdm=marker:ff=unix:noet:ts=4:sw=4
ftplugin/ATP_files/LatexBox_mappings.vim	[[[1
50
" Author:	David Mungerd
" Maintainer:	Marcin Szamotulski
" Note:		This file is a part of Automatic Tex Plugin for Vim.
" Language:	tex
" Last Change:

let s:loaded = ( !exists("s:loaded") ? 1 : s:loaded+1 )

" begin/end pairs [[[
nmap <buffer> <silent> %    <Plug>LatexBox_JumpToMatch
nmap <buffer> <silent> g%   <Plug>LatexBox_BackJumpToMatch
xmap <buffer> <silent> %    <Plug>LatexBox_JumpToMatch
omap <buffer> <silent> <expr> % ( matchstr(getline("."), '^.*\%'.(col(".")+1).'c\\\=\w*\ze') =~ '\\\(begin\\|end\)$' ? ":<C-U>normal V%<CR>" : ":<C-U>normal v%<CR>" )
xmap <buffer> <silent> g% <Plug>LatexBox_BackJumpToMatch
vmap <buffer> <silent> ie <Plug>LatexBox_SelectCurrentEnvInner
vmap <buffer> <silent> iE <Plug>LatexBox_SelectCurrentEnVInner
vmap <buffer> <silent> ae <Plug>LatexBox_SelectCurrentEnvOuter
omap <buffer> <silent> ie :normal vie<CR>
omap <buffer> <silent> ae :normal vae<CR>
vmap <buffer> <silent> im <Plug>LatexBox_SelectInlineMathInner
vmap <buffer> <silent> am <Plug>LatexBox_SelectInlineMathOuter
omap <buffer> <silent> im :normal vim<CR>
omap <buffer> <silent> am :normal vam<CR>

vmap <buffer> <silent> i( <Plug>LatexBox_SelectBracketInner_1
omap <buffer> <silent> i( :normal vi(<CR>
vmap <buffer> <silent> a( <Plug>LatexBox_SelectBracketOuter_1
omap <buffer> <silent> a( :normal va(<CR>
vmap <buffer> <silent> i) <Plug>LatexBox_SelectBracketInner_1
omap <buffer> <silent> i) :normal vi)<CR>
vmap <buffer> <silent> a) <Plug>LatexBox_SelectBracketOuter_1
omap <buffer> <silent> a) :normal va)<CR>

vmap <buffer> <silent> i{ <Plug>LatexBox_SelectBracketInner_2
omap <buffer> <silent> i{ :normal vi{<CR>
vmap <buffer> <silent> a{ <Plug>LatexBox_SelectBracketOuter_2
omap <buffer> <silent> a{ :normal va{<CR>
vmap <buffer> <silent> i} <Plug>LatexBox_SelectBracketInner_2
omap <buffer> <silent> i} :normal vi}<CR>
vmap <buffer> <silent> a} <Plug>LatexBox_SelectBracketOuter_2
omap <buffer> <silent> a} :normal va}<CR>

vmap <buffer> i[ <Plug>LatexBox_SelectBracketInner_3
omap <buffer> i[ :normal vi[<CR>
vmap <buffer> a[ <Plug>LatexBox_SelectBracketOuter_3
omap <buffer> a[ :normal va[<CR>
vmap <buffer> i] <Plug>LatexBox_SelectBracketInner_3
omap <buffer> i] :normal vi]<CR>
vmap <buffer> a] <Plug>LatexBox_SelectBracketOuter_3
omap <buffer> a] :normal va]<CR>
ftplugin/ATP_files/LatexBox_motion.vim	[[[1
1025
" Language:	tex
" Author:	David Mnuger (latexbox vim plugin)
" Maintainer:	Marcin Szamotulski
" Note:		This file is a part of Automatic Tex Plugin for Vim.
" Language:	tex
" Last Change:

" Some things is enough to source once
let s:sourced = exists("s:sourced") ? 1 : 0

if !s:sourced || g:atp_reload_functions
" HasSyntax {{{
" s:HasSyntax(syntaxName, [line], [col])
function! s:HasSyntax(syntaxName, ...)
	let line	= a:0 >= 1 ? a:1 : line('.')
	let col		= a:0 >= 2 ? a:2 : col('.')
	return index(map(synstack(line, col), 'synIDattr(v:val, "name") == "' . a:syntaxName . '"'), 1) >= 0
endfunction
" }}}

" Search and Skip Comments {{{
" s:SearchAndSkipComments(pattern, [flags], [stopline])
function! s:SearchAndSkipComments(pat, ...)
	let flags	= a:0 >= 1 ? a:1 : ''
	let stopline	= a:0 >= 2 ? a:2 : 0
	let saved_pos 	= getpos('.')

	" search once
	let ret = search(a:pat, flags, stopline)

	if ret
		" do not match at current position if inside comment
		let flags = substitute(flags, 'c', '', 'g')

		" keep searching while in comment
		while LatexBox_InComment()
			let ret = search(a:pat, flags, stopline)
			if !ret
				break
			endif
		endwhile
	endif

	if !ret
		" if no match found, restore position
		call setpos('.', saved_pos)
	endif

	return ret
endfunction
" }}}

" begin/end pairs {{{
"
" s:JumpToMatch(mode, [backward])
" - search backwards if backward is given and nonzero
" - search forward otherwise
"
function! s:JumpToMatch(mode, ...)

    	if a:0 >= 1
	    let backward = a:1
	else
	    let backward = 0
	endif

	" add current position to the jump-list (see :help jump-motions)
	normal! m`

	let sflags = backward ? 'cbW' : 'cW'

	" selection is lost upon function call, reselect
	if a:mode == 'v'
		normal! gv
	endif

	" open/close pairs (dollars signs are treated apart)
	let open_pats 		= ['\\begin\>', '{', '\[', '(', '\\left\>', '\\lceil\>', '\\lgroup\>', '\\lfloor', '\\langle']
	let close_pats 		= ['\\end\>', '}', '\]', ')', '\\right\>', '\\rceil', '\\rgroup\>', '\\rfloor', '\\rangle']
	let dollar_pat 		= '\\\@<!\$'
	let two_dollar_pat 	= '\\\@<!\$\$'

	let saved_pos = getpos('.')
	let beg_of_line  = strpart(getline('.'), 0, searchpos('\>', 'n')[1]-1)

	" move to the left until not on alphabetic characters
	call search('\A', 'cbW', line('.'))
	if getline('.')[col('.')-1]=~'}\|\]\|)' && col('.') < saved_pos[2]
	    normal! l
	endif

	let zonex=s:HasSyntax('texMathZoneX', line("."), col(".")) || s:HasSyntax('texMathZoneX', line('.'), max([1, col(".")-1])) 
	let zoney=s:HasSyntax('texMathZoneY', line("."), col("."))  

	let stopline = ( g:atp_VimCompatible || g:atp_VimCompatible =~? '\<yes\>' ? line('.') : 0 )
	" go to next opening/closing pattern on same line (depends on
	" g:atp_VimCompatible)
	if expand("<cWORD>") !~? '\\item'
	    if !s:HasSyntax('texSectionModifier', line('.'), col('.'))
		let pos = !s:SearchAndSkipComments(
					\	'\m\C\%(' . join(open_pats + close_pats + [dollar_pat], '\|') . '\)',
					\	sflags, stopline)
	    else
		let pos = !s:SearchAndSkipComments(
					\	'\m\C\%(' . join(open_pats + close_pats, '\|') . '\)',
					\	sflags, stopline)
	    endif
	    " THE line('.') above blocks it from working not just in one line
	    " (especially with \begin:\end which might be in different lines).
	    if pos
		    " abort if no match or if match is inside a comment
		    call setpos('.', saved_pos)
		    return
	    endif
	endif

	let rest_of_line = strpart(getline('.'), col('.') - 1)

	" match for '$' pairs
	if rest_of_line =~ '^\$' && beg_of_line !~ '\C\\item$' && !s:HasSyntax('texSectionModifier', line('.'), col('.'))

		" check if next character is in inline math
		let zonex+=s:HasSyntax('texMathZoneX', line("."), col(".")) 
		let zoney+=s:HasSyntax('texMathZoneY', line("."), col(".")) || s:HasSyntax('texMathZoneY', line('.'), max([1, col(".")-1])) 
		let [lnum, cnum] = searchpos('.', 'nW')

		if zonex
		    if lnum && s:HasSyntax('texMathZoneX', lnum, cnum)
			    call s:SearchAndSkipComments(dollar_pat, 'W')
		    else
			    call s:SearchAndSkipComments(dollar_pat, 'bW')
		    endif
		elseif zoney
		    if lnum && s:HasSyntax('texMathZoneY', lnum, cnum)
			    call s:SearchAndSkipComments(two_dollar_pat, 'W')
		    else
			    call s:SearchAndSkipComments(two_dollar_pat, 'bW')
		    endif
		endif
	else

	" match other pairs
	for i in range(len(open_pats))
		let open_pat = open_pats[i]
		let close_pat = close_pats[i]
		let mid_pat = ( open_pat  == '\\begin\>' ? '\C\\item\>' : '' )

		if mid_pat != "" && beg_of_line =~ '\C\%(' . mid_pat . '\)$'
		    " if on mid pattern
		    call search('\C'.mid_pat, 'Wbc', line("."))
		    call searchpair('\C'.open_pat, mid_pat, '\C'.close_pat, 'W'.(backward ? 'b' : ''), 'LatexBox_InComment()')
		    break
		elseif rest_of_line =~ '^\C\%(' . open_pat . '\)'
		    " if on opening pattern, go to closing pattern
		    call searchpair('\C'.open_pat, 
				\ (!backward && (saved_pos[1] == line('.') && saved_pos[2] >= col('.')) ? mid_pat : ''),
				\ '\C'.close_pat, 'W', 'LatexBox_InComment()')
		    break
		elseif rest_of_line =~ '^\C\%(' . close_pat . '\)'
		    " if on closing pattern, go to opening pattern
		    call searchpair('\C'.open_pat, (!backward ? '' : mid_pat), '\C'.close_pat, 'Wb', 'LatexBox_InComment()')
		    break
		endif

	endfor
    endif

endfunction

nnoremap <silent> <Plug>LatexBox_JumpToMatch		:call <SID>JumpToMatch('n')<CR>
vnoremap <silent> <Plug>LatexBox_JumpToMatch 		:<C-U>call <SID>JumpToMatch('v')<CR>
nnoremap <silent> <Plug>LatexBox_BackJumpToMatch 	:call <SID>JumpToMatch('n', 1)<CR>
vnoremap <silent> <Plug>LatexBox_BackJumpToMatch 	:<C-U>call <SID>JumpToMatch('v', 1)<CR>
" }}}

" select inline math {{{
" s:SelectInlineMath(seltype)
" where seltype is either 'inner' or 'outer'
function! s:SelectInlineMath(seltype)

    	let saved_pos		= getpos('.')

	let synstack		= map(synstack(line("."),col(".")), 'synIDattr(v:val, "name")')

	if len(filter(synstack, "v:val =~ '^texMathZone[A-L]S\\?'"))
	    call s:SelectCurrentEnv(a:seltype)
	    return
	endif

	let ZoneX_pat_O 	= '\\\@<!\$'
	let ZoneX_pat_C 	= '\\\@<!\$'
	let ZoneY_pat_O 	= '\\\@<!\$\$'
	let ZoneY_pat_C 	= a:seltype == 'inner' ? '\\\@<!\$\$' 	: '\\\@<!\$\$'
	let ZoneV_pat_O		= '\\\@<!\\('
	let ZoneV_pat_C		= a:seltype == 'inner' ? '\\\@<!\\)' 	: '\\\@<!\\\zs)' 
	let ZoneW_pat_O		= '\\\@<!\\\['
	let ZoneW_pat_C		= a:seltype == 'inner' ? '\\\@<!\\\]'	: '\\\@<!\\\zs\]'

	if 	( s:HasSyntax('texMathZoneV', line("."), max([1,col(".")-1])) ||
		\ s:HasSyntax('texMathZoneW', line("."), max([1,col(".")-1])) ||
		\ s:HasSyntax('texMathZoneX', line("."), max([1,col(".")-1])) ||
		\ s:HasSyntax('texMathZoneY', line("."), max([1,col(".")-1])) && b:atp_TexFlavor == 'plaintex' )  && 
		\ col(".") > 1
	    normal! h
	elseif 	( s:HasSyntax('texMathZoneV', line("."), max([1,col(".")-2])) ||
		\ s:HasSyntax('texMathZoneW', line("."), max([1,col(".")-2])) ||
		\ s:HasSyntax('texMathZoneY', line("."), max([1,col(".")-2])) && b:atp_TexFlavor == 'plaintex' )  && 
		\ col(".") > 2
	    normal! 2h
	endif

	let return 		= 1 
	let math_zones		= ( b:atp_TexFlavor == 'plaintex' ? [ 'V', 'W', 'X', 'Y'] : [ 'V', 'W', 'X'] )
	for L in math_zones
	    if s:HasSyntax('texMathZone'. L, line(".")) ||
			\ s:HasSyntax('texMathZone'. L, line("."), max([1, col(".")-1]))
		    call s:SearchAndSkipComments(Zone{L}_pat_O, 'cbW')
		    let zone 	= L
		    let return 	= 0
	    endif
	endfor


	if return
	    call cursor(saved_pos[1], saved_pos[2])
	    return
	endif

	if a:seltype == 'inner'
	    if zone =~ '^V\|W$' || zone == 'Y' && b:atp_TexFlavor == 'plaintex'
		normal! 2l
	    elseif zone == 'X'
		normal! l
	    endif
	    if getline(".")[col(".")-1] == ' '
		normal! w
	    endif
	endif

	if visualmode() ==# 'V'
		normal! V
	else
		normal! v
	endif

	call s:SearchAndSkipComments(Zone{zone}_pat_C, 'W')

	if a:seltype == 'inner'
	    if getline(".")[col(".")-2] == ' '
		normal! ge
	    else
		if col(".") > 1
		    call cursor(line("."),col(".")-1)
		else
		    call cursor(line(".")-1, len(getline(line(".")-1)))
		endif
	    endif
	endif

	if a:seltype == 'outer' && zone == 'Y'
	    call cursor(line("."),col(".")+1)
	endif
endfunction


vnoremap <silent> <Plug>LatexBox_SelectInlineMathInner :<C-U>call <SID>SelectInlineMath('inner')<CR>
vnoremap <silent> <Plug>LatexBox_SelectInlineMathOuter :<C-U>call <SID>SelectInlineMath('outer')<CR>
" }}}

" {{{ select bracket
function! <SID>LatexBox_SelectBracket(inner, bracket, bracket_sizes)
    " a:bracket_sizes a dictionary of matching bracket sizse { '\bigl' : '\bigr' }.

    " This prevents from matching \(:\) and \[:\] (but not \{:\})
    if a:bracket == '(' || a:bracket == '['
	let pat = '\\\@<!'
    else
	let pat = ''
    endif

    let begin_pos = searchpairpos(pat.escape(a:bracket, '[]\'), '', pat.escape(g:atp_bracket_dict[a:bracket], '[]\'), 'bW')
    if !begin_pos[0]
	let begin_pos=searchpos(pat.escape(a:bracket, '[]\'), 'W', line('.'))
    endif

    if !begin_pos[0]
	return
    endif

    let o_size = matchstr(getline(line("."))[0:col(".")-2], '\\\w*\ze\s*$')
    let b_len = len(matchstr(getline(line("."))[0:col(".")-2], '\\\w*\s*$'))
    let c_size = get(a:bracket_sizes, o_size, "")

    " In the case of \{ 
    if o_size == "\\"
	let add = 1
	let o_size = matchstr(getline(line("."))[0:col(".")-3], '\\\w*\ze\s*$')
	let b_len = len(matchstr(getline(line("."))[0:col(".")-3], '\\\w*\s*$'))+1
	let c_size = get(a:bracket_sizes, o_size, "")
    else 
	let add = 0
    endif

    if a:inner == 'inner'
	call cursor(line("."), col(".")+1)
    else
	if c_size != ""
	    let s_pos = [line("."), col(".")]
	    call cursor(line("."), col(".")-b_len)
	endif
    endif
    let begin_pos  = [ line("."), col(".") ]

    if exists("s_pos")
	call cursor(s_pos)
    endif

    let b_pos = [ line("."), col(".") ]

    let end_pos = searchpairpos(pat.escape(a:bracket, '[]\'), '', pat.escape(g:atp_bracket_dict[a:bracket], '[]\'), 'nW')
    call cursor(end_pos)
    let len	= len(matchstr(getline(".")[0:col(".")-1], 
		    \ escape(c_size, '\'). '\s*'.(add ? '\\': '').'\ze'.escape(g:atp_bracket_dict[a:bracket], '[]\')))

    if a:inner == 'inner'
	let end_pos[1] -= len+1
    endif

    call cursor(begin_pos)

    if visualmode() ==# 'V'
	    normal! V
    else
	    normal! v
    endif

    call cursor(end_pos)

endfunction
vnoremap <silent> <Plug>LatexBox_SelectBracketInner_1 :<C-U>call <SID>LatexBox_SelectBracket('inner', '(', g:atp_sizes_of_brackets)<CR>
vnoremap <silent> <Plug>LatexBox_SelectBracketOuter_1 :<C-U>call <SID>LatexBox_SelectBracket('outer', '(', g:atp_sizes_of_brackets)<CR>
vnoremap <silent> <Plug>LatexBox_SelectBracketInner_2 :<C-U>call <SID>LatexBox_SelectBracket('inner', '{', g:atp_sizes_of_brackets)<CR>
vnoremap <silent> <Plug>LatexBox_SelectBracketOuter_2 :<C-U>call <SID>LatexBox_SelectBracket('outer', '{', g:atp_sizes_of_brackets)<CR>
vnoremap <silent> <Plug>LatexBox_SelectBracketInner_3 :<C-U>call <SID>LatexBox_SelectBracket('inner', '[', g:atp_sizes_of_brackets)<CR>
vnoremap <silent> <Plug>LatexBox_SelectBracketOuter_3 :<C-U>call <SID>LatexBox_SelectBracket('outer', '[', g:atp_sizes_of_brackets)<CR>
" }}}

" {{{ select syntax
" syntax groups 'texDocZone' and 'texSectionZone' need to be synchronized
" before ':syntax sync fromstart' which is quite slow. It is better to provide
" other method of doing this. (If s:SelectSyntax is not syncing the syntax
" then the behaviour is unpredictable).
function! s:SelectSyntax(syntax)

    " mark the current position
    normal! m'

    let synstack	= map(synstack(line("."),col(".")), 'synIDattr(v:val, "name")')
    " there are better method for texDocZone and texSectionZone: 
    call filter(synstack, "v:val != 'texDocZone' && v:val != 'texSectionZone'")
    if  synstack == []
	return

    endif

    if a:syntax == 'inner'

	let len		= len(synstack)
	let syntax	= synstack[max([0, len-1])]

    elseif a:syntax == 'outer'
	let syntax	= synstack[0]

    else
	let syntax	= a:syntax

    endif

    let save_ww		= &l:ww
    set ww		+=b,l
    let save_pos	= getpos(".")	 


    if !count(map(synstack(line("."),col(".")), 'synIDattr(v:val, "name")'), syntax)
	return

    endif

    while count(map(synstack(line("."),col(".")), 'synIDattr(v:val, "name")'), syntax)
	normal! h
	" for some syntax groups do not move to previous line
	if col(".") == 1 && count(['texStatement', 'texTypeSize'], syntax)
	    keepjumps normal! h
	    break
	endif

    endwhile

    " begin offset
    if getpos(".")[2] < len(getline("."))
	call cursor(line("."),col(".")+1)

    else
	call cursor(line(".")+1, 1)

    endif

    if visualmode() ==# 'V'
	normal! V

    else
	normal! v

    endif

    call cursor(save_pos[1], save_pos[2]) 
    while count(map(synstack(line("."),max([1, min([col("."), len(getline("."))])])), 'synIDattr(v:val, "name")'), syntax) || len(getline(".")) == 0 
	keepjumps normal! l
	" for some syntax groups do not move to next line
	if col(".") == len(getline(".")) && count(['texStatement', 'texTypeSize'], syntax)
	    keepjumps normal! l
	    break
	endif
    endwhile

    " end offset
    if len(getline(".")) == 0
	call cursor(line(".")-1,len(getline(line(".")-1)))
    endif
    if count(['texParen', 'texLength', 'Delimiter', 'texStatement', 'texTypeSize', 'texRefZone', 'texSectionMarker', 'texTypeStyle'], syntax)
	if col(".") > 1
	    call cursor(line("."),col(".")-1)

	else
	    call cursor(line(".")-1,len(getline(line(".")-1)))

	endif
    elseif count(['texMathZoneV', 'texMathZoneW', 'texMathZoneY'], syntax)
	    call cursor(line("."),col(".")+1)

    endif

    let &l:ww	= save_ww
endfunction
" }}}

" select current environment {{{
function! s:SelectCurrentEnv(seltype)
	let [env, lnum, cnum, lnum2, cnum2] = LatexBox_GetCurrentEnvironment(1)
	call cursor(lnum, cnum)
	if a:seltype == 'inner'
		if env =~ '^\'
			call search('\\.\_\s*\S', 'eW')
		else
			call search('}\%(\_\s*\[\_[^]]*\]\)\?\_\s*\S', 'eW')
		endif
	endif
	if visualmode() ==# 'V'
		normal! V
	else
		normal! v
	endif
	call cursor(lnum2, cnum2)
	if a:seltype == 'inner'
		call search('\S\_\s*', 'bW')
	else
		if env =~ '^\'
			normal! l
		else
			call search('}', 'eW')
		endif
	endif
endfunction

function! s:SelectCurrentEnV()
	call s:SelectCurrentEnv('inner')
	execute 'normal o'
	call s:JumpToMatch('n', 1)
	execute 'normal o'
endfunction

" }}}

" Jump to the next braces {{{
"
function! LatexBox_JumpToNextBraces(backward)
	let flags = ''
	if a:backward
		normal h
		let flags .= 'b'
	else
		let flags .= 'c'
	endif
	if search('[][}{]', flags) > 0
		normal l
	endif
	let prev = strpart(getline('.'), col('.') - 2, 1)
	let next = strpart(getline('.'), col('.') - 1, 1)
	if next =~ '[]}]' && prev !~ '[][{}]'
		return "\<Right>"
	else
		return ''
	endif
endfunction
" }}}

" Highlight Matching Pair {{{
" TODO: Redefine NoMatchParen and DoMatchParen functions to handle
" s:HighlightMatchingPair function.
" TODO: do not match for \begin{document}:\end{document}
" 	or limit matches to the window (anyway it is done every time the
" 	cursor moves).
" 	winheight(0)			returns window height
" 	winsaveview()['topline'] 	returns the top line
function! <SID>HighlightMatchingPair()

	2match none

	if LatexBox_InComment()
		return
	endif

" 	let open_pats 		= ['\\begin\>\ze\%(\s*{\s*document\s*}\)\@!', '\\left\>', '\c\\bigg\=\>\%((\|{\|\\{\|\[\)' ]
" 	let close_pats 		= ['\\end\>\ze\%(\s*{\s*document\s*}\)\@!', '\\right\>', '\c\\bigg\=\>\%()\|}\|\\}\|\]\)' ]
	let open_pats 		= ['\\begin\>\ze', '\\left\>', '\c\\bigg\=l\=\>\%((\|{\|\\{\|\[\)', '\\lceil\>', '\\lgroup\>', '\\lfloor', '\\langle' ]
	let close_pats 		= ['\\end\>\ze', '\\right\>', '\c\\bigg\=r\=\>\%()\|}\|\\}\|\]\)', '\\rceil', '\\rgroup\>', '\\rfloor', '\\rangle']
	let dollar_pat 		= '\\\@<!\$'
	let two_dollar_pat 	= '\\\@<!\$\$'

	let saved_pos = getpos('.')

	if getline('.')[col('.') - 1] == '$' && !s:HasSyntax('texSectionModifier', line('.'), col('.'))

	   if strpart(getline('.'), col('.') - 2, 1) == '\'
		   return
	   endif

		" match $-pairs
		let lnum = line('.')
		let cnum = col('.')

		" check if next or previous character is \$
		let two_dollars = ( getline('.')[col('.') - 2] == '$' ? 'p' : 
			    			\ ( getline('.')[col('.') ] == '$' ? 'n' : '0' ) )

		if two_dollars == '0' || b:atp_TexFlavor == 'tex'

		    " check if next character is in inline math
		    let [lnum2, cnum2] = searchpos('.', 'nW')
		    if lnum2 && s:HasSyntax('texMathZoneX', lnum2, cnum2)
			    call s:SearchAndSkipComments(dollar_pat, 'W')
		    else
			    call s:SearchAndSkipComments(dollar_pat, 'bW')
		    endif

		    execute '2match MatchParen /\%(\%' . lnum . 'l\%' . cnum . 'c\$'
					    \	. '\|\%' . line('.') . 'l\%' . col('.') . 'c\$\)/'

		elseif b:atp_TexFlavor == 'plaintex'
		    
		    " check if next character is in inline math
		    if two_dollars == 'n'
			call cursor(line('.'), col('.')+1)
		    endif
		    " position of the openning \$\$
		    let cnum = col('.')-1
		    let [lnum2, cnum2] = searchpos( '.' , 'nW')
		    if lnum2 && s:HasSyntax('texMathZoneY', lnum2, cnum2)
			    call s:SearchAndSkipComments(two_dollar_pat, 'W')
		    else
			" searching backward needs the cursor to be placed
			" before closing $$.
			if col(".") - 2 >= 1
			    call cursor(line("."), col(".")-2)
			else
			    call cursor(line(".")-1, 1) 
			    call cursor(line("."), col("$"))
			endif
			call s:SearchAndSkipComments(two_dollar_pat, 'bW')
		    endif
		    let cnum_e	= cnum+1
		    let cnum_E	= col('.')
		    let cnum_Ee	= cnum_E+1
		    execute '2match MatchParen /\%(\%' . lnum . 'l\%' . cnum . 'c\$'
					    \	. '\|\%' . lnum . 'l\%' . cnum_e . 'c\$'
					    \	. '\|\%' . line('.') . 'l\%' . cnum_E . 'c\$'
					    \	. '\|\%' . line('.') . 'l\%' . cnum_Ee . 'c\$\)/'

		endif

	else
		" match other pairs

		" find first non-alpha character to the left on the same line
		let [lnum, cnum] = searchpos('\A', 'cbW', line('.'))
		if strpart(getline(lnum), 0, cnum)  =~ '\\\%(begin\|end\){[^}]*}\=$'
		    let [lnum, cnum] = searchpos('\\', 'cbW', line('.'))
		endif

		let delim = matchstr(getline(lnum), '^\m\(' . join(open_pats + close_pats, '\|') . '\)', cnum - 1)

		if empty(delim)
			call setpos('.', saved_pos)
			return
		endif

		for i in range(len(open_pats))
			let open_pat = open_pats[i]
			let close_pat = close_pats[i]

			if delim =~# '^' . open_pat
				" if on opening pattern, go to closing pattern
				let stop_line=winheight(0)+winsaveview()['topline']
				call searchpair('\C' . open_pat, '', '\C' . close_pat, 'W', 'LatexBox_InComment()', stop_line)
				execute '2match MatchParen /\%(\%' . lnum . 'l\%' . cnum . 'c' . open_pats[i]
							\	. '\|\%' . line('.') . 'l\%' . col('.') . 'c' . close_pats[i] . '\)/'
				break
			elseif delim =~# '^' . close_pat
				" if on closing pattern, go to opening pattern
				let stop_line=winsaveview()['topline']
				if close_pat =~ '\\end'
				    call searchpair('\C\\begin\>', '', '\C\\end\>\zs'  , 'bW', 'LatexBox_InComment()', stop_line)
				else
				    call searchpair('\C' . open_pat, '', '\C' . close_pat, 'bW', 'LatexBox_InComment()', stop_line)
				endif
				execute '2match MatchParen /\%(\%' . line('.') . 'l\%' . col('.') . 'c' . open_pats[i]
							\	. '\|\%' . lnum . 'l\%' . cnum . 'c' . close_pats[i] . '\)/'
				break
			endif
		endfor
	endif

	call setpos('.', saved_pos)
endfunction
" }}}

" select current paragraph {{{
function! s:InnerSearchPos(begin, line, col, run)
        let cline 	= line(".")
	let ccol	= col(".") 
	call cursor(a:line, a:col)
	if a:begin == 1
	    let flag = 'bnW' . (a:run == 1 ? 'c' : '')
" Note: sometimes it is better is it stops before \\begin some times not,
" maybe it is better to decide for which environment names to stop
" (theorem, ... but not align [mathematical ones]). The same about end few
" lines ahead.
	    let pattern = '\%(^\s*$' . 
			\ '\|\\begin\>\s*{' .
			\ '\|\\\@<!\\\[' . 
			\ '\|\\\@<!\\\]\s*$' . 
			\ '\|^[^%]*\%(\ze\\par\>' . 
				\ '\|\ze\\newline\>' . 
				\ '\|\\end\s*{[^}]*}\s*\zs' . 
				\ '\)' . 
			\ '\|\\item\%(\s*\[[^\]]*\]\)\=' . 
			\ '\|\\\%(part\*\=' . 
				\ '\|chapter\*\=' .
				\ '\|section\*\=' . 
				\ '\|subsection\*\=' . 
				\ '\|subsubsection\*\=' . 
				\ '\|paragraph\*\=' . 
				\ '\|subparagraph\*\=\)\s*\%(\[[^]]*\]\)\=\s*{[^}]*}\s*\%({[^}]*}\)\=' . 
			\ '\|\\opening{[^}]*}' .
			\ '\|\\closing{' .
			\ '\|\\\@<!\$\$\s*$' . 
			\ '\|\\\\\*\=' . 
			\ '\|\\\%(small\|med\|big\)skip' .
			\ '\|\%^\|\%$' . 
			\ '\|^\s*%\)'
	    let [ line, column ] = searchpos(pattern, flag)
" 	    if getline(line) =~ '^\s*%'
" 		let [ line, column ] = [ line+1, 1 ]
" 	    endif
	else
	    let pattern = '\%(^\s*$' . 
			\ '\|\\\@<!\\\]\zs' .
			\ '\|\%(^\s\+\)\=\\end\>\s*{' .
			\ '\|^[^%]*\%(' . 
				\ '\zs\%(^\s\+\)\=\\par\>' .
				\ '\|\zs\(^\s\+\)\=\\newline\>' . 
				\ '\|\%(^\s\+\)\=\\begin\s*{[^}]*}\s*\%(\[[^]]*\]\)\=\)' . 
			\ '\|\%(^\%(\s\|%\)\+\)\=\\item' . 
			\ '\|\%(^\s\+\)\=\\\%(part\*\=' . 
				\ '\|chapter\*\=' . 
				\ '\|section\*\=' . 
				\ '\|subsection\*\=' . 
				\ '\|subsubsection\*\=' . 
				\ '\|paragraph\*\=' . 
				\ '\|subparagraph\*\=\){\(\n\|[^}]\)*}\s*\%(\[[^]]*\]\)\=\s*\%({^}]*}\)\=' . 
			\ '\|\\opening{[^}]*}' .
			\ '\|\\closing{' .
			\ '\|^\s*\\\@<!\\\[' . 
			\ '\|^\s*\\\@<!\$\$' . 
			\ '\|\\\\\*\=' .
			\ '\|\\\%(small\|med\|big\)skip' .
			\ '\|\%^\|\%$\|^\s*\\\@<!%\)'
	    let [ line, column ] = searchpos(pattern, 'nW')
" 	    if getline(line) =~ '^\s*\\\@<!%'
" 		let [ line, column ] = [ line-1, len(getline(line-1))-1 ]
" 	    endif
	endif
	call cursor(cline, ccol)
	return [ line, column ] 
endfunction
if g:atp_debugSelectCurrentParagraph
    command! EchoInnerBegin :echo s:InnerSearchPos(1, line("."), col("."), 1)
    command! EchoInnerEnd :echo s:InnerSearchPos(0, line("."), col("."), 1)
endif


function! s:SelectCurrentParagraph(seltype) 
    if a:seltype == "inner"
	    if getline(line(".")) =~ '^\s*\\\@<!%'
	    call SelectComment()
	    return
	endif
	" inner type ends and start with \[:\] if \[ is at the begining of
	" line (possibly with white spaces) and \] is at the end of line
	" (possibly with white spaces, aswell).
	" This can cause some asymetry. So I prefer the simpler solution: \[:\]
	" alwasy ends inner paragraph. But how I use tex it is 'gantz egal'
	" but this solution can make a difference for some users, so I keep
	" the first way.
	"
	" Find begin position (iterate over math zones).
	let true = 1
	let [ bline, bcol, eline, ecol ] = copy([ line("."), col("."), line("."), col(".") ])
	let i =1
	if g:atp_debugSelectCurrentParagraph
	    call atplib#Log("SelectCurrentParagraph.log", "", "init")
	    call atplib#Log("SelectCurrentParagraph.log", " B pos:" . string([line("."), col(".")]) . " e-pos:" . string([bline, bcol])) 
	endif
	while true
	    let [ bline, bcol ] = s:InnerSearchPos(1, bline, bcol, i)
	    let true = atplib#complete#CheckSyntaxGroups(g:atp_MathZones, bline, bcol) && strpart(getline(bline), bcol-1) !~ '^\\\[\|^\\begin\>'
	    if g:atp_debugSelectCurrentParagraph
		call atplib#Log("SelectCurrentParagraph.log",i . ") " . string([bline, bcol]) . " pos:" . string([line("."), col(".")]) . " true: " . true)
	    endif
	    let i+=1
	endwhile
	if g:atp_debugSelectCurrentParagraph
	    let [ g:bline0, g:bcol0]	= deepcopy([ bline, bcol])
	    let bline_str = strpart(getline(bline), bcol-1)
	    call atplib#Log("SelectCurrentParagraph.log", "[bline, bcol]=".string([ bline, bcol]))
	    call atplib#Log("SelectCurrentParagraph.log", "getline(bline)=".getline(bline))
	    call atplib#Log("SelectCurrentParagraph.log", "bline condition=".(getline(bline) !~ '^\s*$' && getline(bline) !~ '\\begin\s*{\s*\(equation\|align\|inlinemath\|dispayedmath\)\s*}' && bline_str !~ '^\%(\\\[\|\\item\>\|\\begin\>\)'))
	endif
	" Move to the end of match
	let [ cline, ccolumn ] = [ line("."), col(".") ]
	call cursor(bline, bcol)
	let bline_str 		= strpart(getline(bline), bcol-1)
	if getline(bline) =~ '^\s*%'
	   let bline 		= search('^\s*%\@!')
	   let bcol		= 1
	   let no_motion   	= 1
	elseif getline(bline) !~ '^\s*$' && bline_str !~ '^\%(\\\[\|\\item\>\)'
" 	if getline(bline) !~ '^\s*$' && getline(bline) !~ '\\begin\s*{\s*\(equation\|align\|inlinemath\|dispayedmath\)\s*}' && bline_str !~ '^\%(\\\[\|\\item\>\)'
	    let pattern = '\%(^\s*$' . 
			\ '\|^[^%]*\%(\\\zepar\>' . 
			    \ '\|\\\zenewline\>' . 
			    \ '\|\\end\s*{[^}]*}\s*' . 
			    \ '\|\\begin\s*{[^}]*}\s*\%(\%({' . 
				\ '\|\[\)[^]}]*\%(\]' . 
				\ '\|}\)\)\=\s*\%({[^}]*}\)\=\s*\%(\%(\\\%(label\|index\|hypertarget\s*{[^}]*}\s*\)\s*{[^}]*}\)\s*\%(\\footnote\s*\%(\n' . 
					\ '\|[^}]\)*}\)\=' . 
				    \ '\|\s*\%(\\footnote\s*\%(\n' . 
				\ '\|[^}]\)*}\)\s*\%(\\\%(label\|index\|hypertarget\s*{[^}]*}\s*\)\s*{[^}]*}\)\=\)\{0,3}\)' . 
			\ '\|\\item\%(\s*\[[^\]]*\]\)\=' . 
			\ '\|\\\%(part\*\=' . 
			\ '\|chapter\*\=' . 
			\ '\|section\*\=' . 
			\ '\|subsection\*\=' . 
			\ '\|subsubsection\*\=' . 
			\ '\|paragraph\*\=' . 
			\ '\|subparagraph\*\=\)\s*\%(\[[^]]*\]\)\=\s*{[^}]*}\s*\%({[^}]*}\)\=\%(\s*\\\%(label\|hypertarget\s*{[^}]*}\)\s*{[^}]*}\)\{,2}' . 
			\ '\|\\opening{[^}]*}' .
			\ '\|\\closing{' .
			\ '\|\\\@<!\\\]\s*$' . 
			\ '\|\\\@<!\$\$\s*$' . 
			\ '\|\\\\\*\=\%(\[\d\+\w\+\]\)\=' .
			\ '\|\\\%(small\|med\|big\)skip\)'
	    let [ bline, bcol ] = searchpos(pattern, 'ecnW')
	elseif bline_str =~ '^\\item\>\|^\\begin\>' && bcol > 1
	    let bcol -= 1 
	endif
	if g:atp_debugSelectCurrentParagraph
	    call atplib#Log("SelectCurrentParagraph.log",' [bline, bcol]=' . string([bline, bcol]) . " len bline=".len(getline(bline)))
	endif

	" Find end position (iterate over math zones).
	call cursor(bline, len(line(bline)))
	if strpart(getline(bline), bcol-1) =~ '\\begin\>'
	    let [ eline, ecol ] = s:InnerSearchPos(0, bline, len(getline(bline)), 1)
	else
	    let [ eline, ecol ] = s:InnerSearchPos(0, bline, bcol, 1)
	endif
	if g:atp_debugSelectCurrentParagraph
	    call atplib#Log("SelectCurrentParagraph.log", "eline=".eline." ecol=".ecol)
	endif
	let line = strpart(getline(eline), ecol-1)
	let true = atplib#complete#CheckSyntaxGroups(g:atp_MathZones, eline, ecol) && line !~ '^\s*\\\]\|^\s*\\end\>\|^\s*\\begin\>\>'
" 	let true = atplib#complete#CheckSyntaxGroups(g:atp_MathZones, eline, ecol) && line !~ '^\s*\\\]\|^\s*\\end\>'
	let i = 2
	if g:atp_debugSelectCurrentParagraph
	    call atplib#Log("SelectCurrentParagraph.log", " E pos:" . string([line("."), col(".")]) . " e-pos:" . string([eline, ecol]) . " true: " . true)
	endif
	while true
	    let line	= strpart(getline(eline), ecol-1)
	    if g:atp_debugSelectCurrentParagraph
		call atplib#Log("SelectCurrentParagraph.log", i . ") E line=" . line)
	    endif
	    if line =~ '^\\\@<!\%(\\)\|\\\]\|\\\[\|\\\@<!\$\$\)'
		if g:atp_debugSelectCurrentParagraph
		    call atplib#Log("SelectCurrentParagraph.log", i . ") E line break " . eline . " line=" . line)
		endif
		break
	    endif
	    let [ eline, ecol ] = s:InnerSearchPos(0, eline, ecol, i)
	    let true = atplib#complete#CheckSyntaxGroups(g:atp_MathZones, eline, ecol) && line !~ '^\s*\\\]\|^\s*\\end\>\|^\s*\\begin\>\>'
" 	    let true = atplib#complete#CheckSyntaxGroups(g:atp_MathZones, eline, ecol)
	    if g:atp_debugSelectCurrentParagraph
		call atplib#Log("SelectCurrentParagraph.log", i . ") " . string([eline, ecol]) . " pos:" . string([line("."), col(".")]) . " true: " . true)
	    endif
	    let i+=1
	endwhile
	if line !~ '\\end\>'
	    let emove	= ""
	endif
    else
	let [ bline, bcol ] = searchpos('^\s*$\|^[^%]*\zs\\par\>\|\\begin\s*{\s*\%(document\|letter\)\s*}', 'bcnW')
	let [ eline, ecol ] = searchpos('^\s*$\|^[^%]*\zs\\par\>\|\\end\s*{\s*\%(document\|letter\)\s*}\zs', 'nW')
    endif
    
    if g:atp_debugSelectCurrentParagraph
	let [ g:bline, g:bcol]	= deepcopy([ bline, bcol])
	let [ g:eline, g:ecol]	= deepcopy([ eline, ecol])
	call atplib#Log("SelectCurrentParagraph.log", "[bline, bcol]=".string([ bline, bcol]))
	call atplib#Log("SelectCurrentParagraph.log", "[eline, ecol]=".string([ eline, ecol]))
    endif

    let bline_str = strpart(getline(bline), bcol-1)
    let eline_str = strpart(getline(eline), 0, ecol)
    let eeline_str  = strpart(getline(eline), ecol-1)

    if g:atp_debugSelectCurrentParagraph
	let g:bline_str = bline_str
	let g:eline_str = eline_str
	let g:eeline_str = eeline_str
	call atplib#Log("SelectCurrentParagraph.log", "bline_str=".bline_str)
	call atplib#Log("SelectCurrentParagraph.log", "eline_str=".eline_str)
	call atplib#Log("SelectCurrentParagraph.log", "eeline_str=".eeline_str)
    endif

    if getline(bline) =~ '\\par\>\|\\newline\>\|\\begin\s*{\s*\%(document\|letter\)\s*}' || bline_str =~ '^\%(\\\[\|\\item\>\)' || exists("no_motion")
	" move to the beginning of \par
	let bmove	= ''
    else
	" or to the begining of line 
	let bmove 	=  "w"
    endif

    let whichwrap = &whichwrap

    if getline(eline) =~ '\\par\>'
	let emove	= 'gE'
    elseif eline_str  =~ '\\@<!\\\]'
	let emove	= ''
    elseif eeline_str =~ '^\s*\\end\s*{\s*\%(align\%(at\)\=\|equation\|display\%(ed\)\=math'
		\ . '\|array\|eqnarray\|inlinemath\|math\)\*\=\s*}'
	let emove	= 'E'
    elseif eeline_str =~ '^\\closing\>'
	let emove	= 'ge'
    else
	let emove	= 'h'
	set whichwrap+=h
	" This used to be 'ge' as well.
    endif

    if g:atp_debugSelectCurrentParagraph
	let g:bmove = bmove
	let g:emove = emove
	call atplib#Log("SelectCurrentParagraph.log", "bmove=".bmove." emove=".emove)
    endif

    call cursor(bline, bcol)
    if !empty(bmove)
	execute "normal " . bmove
    endif

    if mode() !~ 'v'  
	if visualmode() ==# 'V'
		normal! V
	else
		normal! v
	endif
    endif

    call cursor(eline, ecol)
    if !empty(emove)
	execute "normal " . emove
    endif
    let &whichwrap=whichwrap
endfunction
" }}}

" {{{ select comment
" This only works with lines which begin with the comment sign '%'.
function! SelectComment()
    if getline(".") !~ '^\s*%'
	return
    endif
    call search('^\(\s*%.*\n\)\@<!\zs\(\s*%\)', "cbW")
    if visualmode() ==# 'V'
	    normal! V
    else
	    normal! v
    endif
    call search('\%(^\s*%.*\zs\n\)\%(^\s*%\)\@!', "cW")
endfunction

" {{{ select group
function! SelectEnvironment(name)
    call search('\\begin\s*{\s*'.a:name.'\s*}', "cbW")
"     if visualmode() ==# 'V'
	    normal! V
"     else
" 	    normal! v
"     endif
    call search('\\end\s*{\s*'.a:name.'\s*}', "cW")
endfunction
" }}}

" {{{ LatexBox_HighlightPairs augroup
    augroup LatexBox_HighlightPairs 
      " Replace all matchparen autocommands
      au!
      au! CursorMoved *.tex call s:HighlightMatchingPair()
    augroup END 

" Highlight bold and italic, by M. Szamotulski
" (to add: optionaly only in gui) 
" this function should do that for every \texbf on the screen
" {{{
" THIS IS TOO SLOW:
function! HighlightEmphText()

     let saved_pos	= getpos('.')
     
     let top_line	= winsaveview()['topline']
     let end_line	= top_line + winheight(0)

     call cursor(top_line, 1)

     keepjumps let [start_lnum, start_cnum] = searchpos('\\\%(textbf{\|bf\)\zs', 'W', end_line)
     let [lnum, cnum] = copy([ start_lnum, start_cnum])

     " if there are no matches, return. 
     if [ lnum, cnum] == [0, 0]
	 return
     endif

     while start_lnum <= end_line && [lnum, cnum] != [0, 0]
     
	 let [lnum, cnum] = copy([ start_lnum, start_cnum])

	 if [lnum, cnum] == [ 0, 0]
	     keepjumps call setpos( '.', saved_pos)
	     return
	 endif

	 while s:HasSyntax('texMatcher', lnum, cnum)
	     if cnum < len(getline(lnum))
		 let cnum += 1
	     else
		 let lnum += 1
		 let cnum  = 1
	     endif
	 endwhile

	 if cnum == 1
	     let stop_lnum = lnum-1
	     let stop_cnum = len(getline(stop_lnum))
	 else
	     let stop_lnum = lnum
	     let stop_cnum = cnum
	 endif


	 let start_lnum 	-= 1
	 let start_cnum		-= 1
	 let stop_lnum  	+= 1

	 call matchadd( 'textBold', '\%>' . start_lnum . 'l\%>' . start_cnum . 'c' . '\%<' . stop_lnum . 'l\%<' . stop_cnum . 'c')

	 let [start_lnum, start_cnum] = searchpos('\\\%(textbf{\|bf\)\zs', 'W', end_line)

     endwhile

     keepjumps call setpos( '.', saved_pos)

"      return [start_lnum, start_cnum, stop_lnum, stop_cnum]
 endfunction
" the 2match function can be run once:
" call s:HighlightEmphText()
"     augroup HighlightEmphText
"       " Replace all matchparen autocommands
"       autocmd CursorMoved *.tex call HighlightEmphText()
"     augroup END
" }}}
endif

" Mappings:
vnoremap <silent> <buffer> <Plug>SelectInnerSyntax 	<ESC>:<C-U>call <SID>SelectSyntax('inner')<CR>
vnoremap <silent> <buffer> <Plug>SelectOuterSyntax 	<ESC>:<C-U>call <SID>SelectSyntax('outer')<CR>
vnoremap <silent> <Plug>LatexBox_SelectCurrentEnvInner 	:<C-U>call <SID>SelectCurrentEnv('inner')<CR>
vnoremap <silent> <Plug>LatexBox_SelectCurrentEnVInner 	:<C-U>call <SID>SelectCurrentEnV()<CR>
vnoremap <silent> <Plug>LatexBox_SelectCurrentEnvOuter 	:<C-U>call <SID>SelectCurrentEnv('outer')<CR>
vnoremap <silent> <Plug>ATP_SelectCurrentParagraphInner :<C-U>call <SID>SelectCurrentParagraph('inner')<CR>
vnoremap <silent> <Plug>ATP_SelectCurrentParagraphOuter :<C-U>call <SID>SelectCurrentParagraph('outer')<CR>
vmap <silent><buffer> <Plug>vSelectComment 		:<C-U>call SelectComment()<CR>
nmap <silent><buffer> <Plug>SelectFrameEnvironment	:call SelectEnvironment('frame')<CR>
" vmap <silent><buffer> <Plug>vSelectFrameEnvironment	:<C-U>call <SID>SelectEnvironment('frame')<CR>
"}}}

ftplugin/ATP_files/abbreviations.vim	[[[1
157
" Author:	Marcin Szmotulski
" Description:  This file contains abbreviations defined in ATP.
" Note:		This file is a part of Automatic Tex Plugin for Vim.
" Language:	tex
" Last Change:

if exists("g:atp_no_abbreviations") && g:atp_no_abbreviations == 1
    finish
endif

iabbrev <buffer> +- 	\pm
iabbrev <buffer> -+ 	\mp
iabbrev <buffer> +\| 	\dagger
iabbrev <buffer> ++ 	\ddagger

" LaTeX Environments
if empty(maparg(g:atp_iabbrev_leader . "document" . g:atp_iabbrev_leader, "i", 1))
    execute "iabbrev <buffer> ".g:atp_iabbrev_leader."document".g:atp_iabbrev_leader."	\begin{document}<CR>\end{document}<Esc>O"
endif
if empty(maparg(g:atp_iabbrev_leader . "description" . g:atp_iabbrev_leader, "i", 1))
    execute "iabbrev <buffer> ".g:atp_iabbrev_leader."description".g:atp_iabbrev_leader." \begin{description}<CR>\end{description}<Esc>O"
endif
if empty(maparg(g:atp_iabbrev_leader . "letter" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'letter'.g:atp_iabbrev_leader.'	\begin{letter}<CR>\end{letter}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "picture" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'picture'.g:atp_iabbrev_leader.'	\begin{picture}()()<CR>\end{picture}<Esc><Up>f(a'
endif
if empty(maparg(g:atp_iabbrev_leader . "list" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'list'.g:atp_iabbrev_leader.'	\begin{list}<CR>\end{list}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "minipage" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'minipage'.g:atp_iabbrev_leader.'	\begin{minipage}<CR>\end{minipage}<Esc><Up>A'
endif
if empty(maparg(g:atp_iabbrev_leader . "titlepage" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'titlepage'.g:atp_iabbrev_leader.'	\begin{titlepage}<CR>\end{titlepage}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "bibliography" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'bibliography'.g:atp_iabbrev_leader.' \begin{thebibliography}<CR>\end{thebibliography}<Esc><Up>A'
endif
if empty(maparg(g:atp_iabbrev_leader . "thebibliography" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'thebibliography'.g:atp_iabbrev_leader.' \begin{thebibliography}<CR>\end{thebibliography}<Esc><Up>A'
endif
if empty(maparg(g:atp_iabbrev_leader . "center" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'center'.g:atp_iabbrev_leader.'	\begin{center}<CR>\end{center}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "flushright" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'flushright'.g:atp_iabbrev_leader.'	\begin{flushright}<CR>\end{flushright}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "flushleft" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'flushleft'.g:atp_iabbrev_leader.'	\begin{flushleft}<CR>\end{flushleft}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "tikzpicture" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'tikzpicture'.g:atp_iabbrev_leader.'	\begin{tikzpicture}<CR>\end{tikzpicture}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "frame" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'frame'.g:atp_iabbrev_leader.'	\begin{frame}<CR>\end{frame}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "itemize" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'itemize'.g:atp_iabbrev_leader.'	\begin{itemize}<CR>\end{itemize}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "enumerate" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'enumerate'.g:atp_iabbrev_leader.'	\begin{enumerate}<CR>\end{enumerate}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "quote" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'quote'.g:atp_iabbrev_leader.'	\begin{quote}<CR>\end{quote}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "quotation" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'quotation'.g:atp_iabbrev_leader.'	\begin{quotation}<CR>\end{quotation}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "verse" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'verse'.g:atp_iabbrev_leader.'	\begin{verse}<CR>\end{verse}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "abstract" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'abstract'.g:atp_iabbrev_leader.'	\begin{abstract}<CR>\end{abstract}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "verbatim" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'verbatim'.g:atp_iabbrev_leader.'	\begin{verbatim}<CR>\end{verbatim}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "figure" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'figure'.g:atp_iabbrev_leader.'	\begin{figure}<CR>\end{figure}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "array" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'array'.g:atp_iabbrev_leader.'	\begin{array}<CR>\end{array}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "table" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'table'.g:atp_iabbrev_leader.'	\begin{table}<CR>\end{table}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "tabular" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'tabular'.g:atp_iabbrev_leader.'	\begin{tabular}<CR>\end{tabular}<Esc><Up>A'
endif

" AMS Stuff
if empty(maparg(g:atp_iabbrev_leader . "equation" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'equation'.g:atp_iabbrev_leader.'	\begin{equation}<CR>\end{equation}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "equation\\*" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'equation*'.g:atp_iabbrev_leader.'	\begin{equation*}<CR>\end{equation*}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "align" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'align'.g:atp_iabbrev_leader.'	\begin{align}<CR>\end{align}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "align\\*" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'align*'.g:atp_iabbrev_leader.'	\begin{align*}<CR>\end{align*}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "alignat" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'alignat'.g:atp_iabbrev_leader.'	\begin{alignat}<CR>\end{alignat}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "alignat\\*" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'alignat*'.g:atp_iabbrev_leader.'	\begin{alignat*}<CR>\end{alignat*}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "gather" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'gather'.g:atp_iabbrev_leader.'	\begin{gather}<CR>\end{gather}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "gather\\*" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'gather*'.g:atp_iabbrev_leader.'	\begin{gather*}<CR>\end{gather*}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "multline" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'multline'.g:atp_iabbrev_leader.'	\begin{multline}<CR>\end{multline}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "multline\\*" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'multline*'.g:atp_iabbrev_leader.'	\begin{multline*}<CR>\end{multline*}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "split" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'split'.g:atp_iabbrev_leader.'	\begin{split}<CR>\end{split}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "flalign" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'flalign'.g:atp_iabbrev_leader.'	\begin{flalign}<CR>\end{flalign}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "flalign\\*" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'flalign*'.g:atp_iabbrev_leader.'	\begin{flalign*}<CR>\end{flalign*}<Esc>O'
endif

if empty(maparg(g:atp_iabbrev_leader . "corollary" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'corollary'.g:atp_iabbrev_leader.'	\begin{corollary}<CR>\end{corollary}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "theorem" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'theorem'.g:atp_iabbrev_leader.'	\begin{theorem}<CR>\end{theorem}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "proposition" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'proposition'.g:atp_iabbrev_leader.'	\begin{proposition}<CR>\end{proposition}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "lemma" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'lemma'.g:atp_iabbrev_leader.'	\begin{lemma}<CR>\end{lemma}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "definition" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'definition'.g:atp_iabbrev_leader.'	\begin{definition}<CR>\end{definition}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "proof" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'proof'.g:atp_iabbrev_leader.'	\begin{proof}<CR>\end{proof}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "remark" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'remark'.g:atp_iabbrev_leader.'	\begin{remark}<CR>\end{remark}<Esc>O'
endif
if empty(maparg(g:atp_iabbrev_leader . "example" . g:atp_iabbrev_leader, "i", 1))
    execute 'iabbrev <buffer> '.g:atp_iabbrev_leader.'example'.g:atp_iabbrev_leader.'	\begin{example}<CR>\end{example}<Esc>O'
endif
ftplugin/ATP_files/atp_RevSearch.py	[[[1
132
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Marcin Szamotulski <mszamot[@]gmail[.]com>
# This script is a part of Automatic TeX Plugin for Vim.
# It can be destributed seprately under General Public Licence ver.3 or higher.

# SYNTAX:
# atp_RevSearch.py <file> <line_nr> [<col_nr>]

# DESRIPTION: 
# This is a python sctipt which implements reverse searching (okular->vim)
# it uses atplib#FindAndOpen() function which finds the vimserver which hosts
# the <file>, then opens it on the <line_nr> and column <col_nr>.
# Column number is an optoinal argument if not set on the command line it is 1.

# HOW TO CONFIGURE OKULAR to get Reverse Search
# Designed to put in okular: 
# 		Settings>Configure Okular>Editor
# Choose: Custom Text Edit
# In the command field type: atp_RevSearch.py '%f' '%l'
# If it is not in your $PATH put the full path of the script.

# DEBUG:
# debug file : /tmp/atp_RevSearch.debug

import subprocess, sys, re, optparse, os
from optparse import OptionParser
from os import devnull

usage   = "usage: %prog [options]"
parser  = OptionParser(usage=usage)
parser.add_option("--vim", dest="vim", action="store_false", default=True)
parser.add_option("--synctex", dest="synctex", action="store_true", default=False)
(options, args) = parser.parse_args()
if options.vim:
    progname = "gvim"
else:
    progname = "vim"

f = open('/tmp/atp_RevSearch.debug', 'w')

def vim_remote_expr(servername, expr):
# Send <expr> to vim server,

# expr must be well quoted:
#       vim_remote_expr('GVIM', "atplib#callback#TexReturnCode()")
    cmd=[progname, '--servername', servername, '--remote-expr', expr]
    devnull=open(os.devnull, "w+")
    subprocess.Popen(cmd, stdout=devnull, stderr=f).wait()
    devnull.close()

# Get list of vim servers.
output  = subprocess.Popen([progname, "--serverlist"], stdout=subprocess.PIPE)
servers = output.stdout.read().decode().split("\n")
server_list = filter(lambda x: len(x),servers)
print(server_list)
file    = args[0]
output_file = file
if not options.synctex:
    line=args[1]
    # Get the column (it is an optional argument)
    if (len(args) >= 3 and int(args[2]) > 0):
            column = str(args[2])
    else:
            column = str(1)
    synctex_returncode  = 0
else:
    # Run synctex
    page=args[1]
    x=args[2]
    y=args[3]
    if x == "0" and y == "0":
        f.close()
        sys.exit("-1")
    y=float(791.333)-float(y)
    synctex_cmd=["synctex", "edit", "-o", str(page)+":"+str(x)+":"+str(y)+":"+str(file)]
    f.write('>>> synctex     '+' '.join(synctex_cmd)+"\n")
    synctex=subprocess.Popen(synctex_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    synctex.wait()
    synctex_output      = synctex.stdout.read()
    synctex_error       = synctex.stderr.read()
    synctex_error_list  = re.split('\n',synctex_error)
    synctex_returncode  = synctex.returncode
    error               = ""
    f.write('>>> synctex return code: '+str(synctex.returncode)+"\n")
    for error_line in synctex_error_list:
        if re.match('SyncTeX ERROR', error_line):
            error=error_line
            f.write(">>> synctex error      : "+error+"\n")
            break
    if synctex.returncode == 0:
        match_pos=re.findall("(?:Line:(-?\d+)|Column:(-?\d+))",synctex_output)
        if len(match_pos):
            line=match_pos[0][0]
            column=match_pos[1][1]
            if column == "-1":
                column = "1"
        else:
            line        = "-1"
            column      = "-1"
        match_pos=re.findall("Input:(.*)",synctex_output)
        f.write(">>>X "+str(match_pos))
        if len(match_pos):
            file = match_pos[0]
    else:
        print("synctex return code: "+str(synctex.returncode))
        line    = "-1"
        column  = "-1"

f.write(">>> args        "+file+":"+line+":"+column+"\n")

if len(server_list):
    server = server_list[0]

    f.write(">>> server: "+server+"\n")
    # Call atplib#FindAndOpen()     
    cmd=progname+" --servername "+server+" --remote-expr \"atplib#FindAndOpen('"+file+"','"+output_file+"','"+line+"','"+column+"')\""
    findandopen=subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
    vim_server=re.split("\n",findandopen.stdout.read())[0]
    f.write('>>> vim server: '+vim_server+"\n")
    if synctex_returncode != 0 and vim_server != "":
        cmd=""
        if error != "":
            vim_remote_expr(vim_server, "atplib#callback#Echo('[ATP:] "+error+"','echomsg','WarninMsg', '1')")
        else:
            vim_remote_expr(vim_server, "atplib#callback#Echo(\"[SyncTex:] synctex return with exit code: "+str(synctex.returncode)+"\",'echo','WarninMsg', '1')")
# Debug:
if len(server_list):
	f.write(">>> file        "+file+"\n>>> line        "+line+"\n>>> column      "+column+"\n>>> cmd         "+cmd+"\n")
else:
	f.write(">>> file        "+file+"\n>>> line        "+line+"\n>>> column      "+column+"\n>>> server       not found\n")
f.close()
ftplugin/ATP_files/common.vim	[[[1
392
" Author:      Marcin Szamotulski
" Description: This script has functions which have to be called before ATP_files/options.vim 
" Note:	       This file is a part of Automatic Tex Plugin for Vim.
" Language:    tex
" Last Change: Tue Dec 06, 2011 at 13:31:10  +0000

" This file contains set of functions which are needed to set to set the atp
" options and some common tools.

let s:sourced 	= exists("s:sourced") ? 1 : 0

" {{{ Variables
if !exists("g:askfortheoutdir") || g:atp_reload_variables
    let g:askfortheoutdir = 0
endif
if !exists("g:atp_raw_texinputs")
    let g:atp_raw_texinputs = substitute(substitute(substitute(system("kpsewhich -show-path tex"),'!!','','g'),'\/\/\+','\/','g'), ':\|\n', ',', 'g')
"     lockvar g:atp_raw_texinputs
endif

" atp tex and bib inputs directories (kpsewhich)
if !exists("g:atp_texinputs") || g:atp_reload_variables
    let path_list	= split(g:atp_raw_texinputs, ',')
    let idx		= index(path_list, '.')
    if idx != -1
	let dot = remove(path_list, index(path_list,'.')) . ","
    else
	let dot = ""
    endif
    call map(path_list, 'v:val . "**"')

    let g:atp_texinputs	= dot . join(path_list, ',')
endif
" a list where tex looks for bib files
" It must be defined before atplib#common#SetProjectName function.
if !exists("g:atp_raw_bibinputs") || g:atp_reload_variables

    let g:atp_raw_bibinputs=substitute(substitute(substitute(
		\ system("kpsewhich -show-path bib"),
		\ '\/\/\+',	'\/',	'g'),	
		\ '!\|\n',	'',	'g'),
		\ ':',		',' ,	'g')
endif
if !exists("g:atp_bibinputs") || g:atp_reload_variables
    let path_list	= split(g:atp_raw_bibinputs, ',')
    let idx		= index(path_list, '.')
    if idx != -1
	let dot = remove(path_list, index(path_list,'.')) . ","
    else
	let dot = ""
    endif
    call map(path_list, 'v:val . "**"')

    let g:atp_bibinputs	= dot . join(path_list, ',')
endif
" }}}

augroup ATP_SetErrorFile
    au BufEnter 	*.tex 		call atplib#common#SetErrorFile()
"     au BufEnter 	$l:errorfile 	setl autoread 
augroup END

" TreeOfFiles
function! TreeOfFiles(main_file,...) "{{{1
    let pattern		= a:0 >= 1 	? a:1 : g:atp_inputfile_pattern
    let flat		= a:0 >= 2	? a:2 : 0	
    let run_nr		= a:0 >= 3	? a:3 : 1 
    let time=reltime()
    if has("python") && &filetype != "plaintex" && ( !exists("g:atp_no_python") || g:atp_no_python == 0 )
	" It was not tested on plaintex files.
	call atplib#search#TreeOfFiles_py(a:main_file)
    else
	call atplib#search#TreeOfFiles_vim(a:main_file, pattern, flat, run_nr)
    endif
    " Notes: vim script avrage is 0.38s, python avrage is 0.28
    return [ b:TreeOfFiles, b:ListOfFiles, b:TypeDict, b:LevelDict ]
endfunction "}}}1

" All Status Line related things:
"{{{ Status Line
function! s:StatusOutDir() "{{{
let status=""
if exists("b:atp_OutDir")
    if b:atp_OutDir != "" 
	let status= status . "Output dir: " . pathshorten(substitute(b:atp_OutDir,"\/\s*$","","")) 
    else
	let status= status . "Please set the Output directory, b:atp_OutDir"
    endif
endif	
    return status
endfunction 
"}}}

" There is a copy of this variable in compiler.vim
function! ATPRunning() "{{{

    if !g:atp_statusNotif
	" Do not put any message if user dosn't want it. 
	return ""
    endif

    if !exists("g:atp_DEV_no_check") || !g:atp_DEV_no_check
    if g:atp_Compiler =~ '\<python' 
        " For python compiler
        for var in [ "Latex", "Bibtex", "Python" ] 
	    if !exists("b:atp_".var."PIDs")
		let b:atp_{var}PIDs = []
	    endif
	    call atplib#callback#PIDsRunning("b:atp_".var."PIDs")
	endfor
	if len(b:atp_LatexPIDs) > 0
	    let atp_running= len(b:atp_LatexPIDs) 
	elseif len(b:atp_BibtexPIDs) > 0
	    let atp_running= len(b:atp_BibtexPIDs)
	else
	    return ''
	endif
    else
	" for g:atp_Compiler='bash' 
	let atp_running=b:atp_running

	for cmd in keys(g:CompilerMsg_Dict) 
	    if b:atp_TexCompiler =~ '^\s*' . cmd . '\s*$'
		let Compiler = g:CompilerMsg_Dict[cmd]
		break
	    else
		let Compiler = b:atp_TexCompiler
	    endif
	endfor
	if atp_running >= 2
	    return atp_running." ".Compiler
	elseif atp_running >= 1
	    return Compiler
	else
	    return ""
	endif
    endif
    endif

    for cmd in keys(g:CompilerMsg_Dict) 
	if b:atp_TexCompiler =~ '^\s*' . cmd . '\s*$'
	    let Compiler = g:CompilerMsg_Dict[cmd]
	    break
	else
	    let Compiler = b:atp_TexCompiler
	endif
    endfor

    " For g:atp_Compiler='python'
    if exists("g:atp_callback") && g:atp_callback
	if exists("b:atp_LatexPIDs") && len(b:atp_LatexPIDs)>0  


	    if exists("g:atp_ProgressBarValues") && type(g:atp_ProgressBarValues) == 4 && get(g:atp_ProgressBarValues,bufnr("%"), {}) != {}
		let max = max(values(get(g:atp_ProgressBarValues, bufnr("%"))))
		let progress_bar="[".max."]".( g:atp_statusOutDir ? " " : "" )
	    else
		let progress_bar=""
	    endif

	    if atp_running >= 2
		return atp_running." ".Compiler." ".progress_bar
	    elseif atp_running >= 1
		return Compiler." ".progress_bar
	    else
		return ""
	    endif
	elseif exists("b:atp_BibtexPIDs") && len(b:atp_BibtexPIDs)>0
	    return b:atp_BibCompiler
	elseif exists("b:atp_MakeindexPIDs") && len(b:atp_MakeindexPIDs)>0
	    return "makeindex"
	endif
    else
	if g:atp_ProgressBar
	    try
		let pb_file = readfile(g:atp_ProgressBarFile)
	    catch /.*:/
		let pb_file = []
	    endtry
	    if len(pb_file)
		let progressbar = Compiler." [".get(pb_file, 0, "")."]"
" 		let progressbar = Compiler
	    else
		let progressbar = ""
	    endif
	else
	    let progressbar = ""
	endif
	return progressbar
    endif
    return ""
endfunction "}}}

" augroup ATP_RedrawStatus
"     au!
"     au CursorHoldI,CursorHold *	:let &ro=&ro
" augroup END

" {{{ Syntax and Hilighting
" ToDo:
" syntax 	match 	atp_statustitle 	/.*/ 
" syntax 	match 	atp_statussection 	/.*/ 
" syntax 	match 	atp_statusoutdir 	/.*/ 
" hi 	link 	atp_statustitle 	Number
" hi 	link 	atp_statussection 	Title
" hi 	link 	atp_statusoutdir 	String
" }}}

function! s:SetNotificationColor() "{{{
    " use the value of the variable g:atp_notification_{g:colors_name}_guibg
    " if it doesn't exists use the default value (the same as the value of StatusLine
    " (it handles also the reverse option!)
    let colors_name = exists("g:colors_name") ? g:colors_name : "default"
"     let g:cname	= colors_name
" 	Note: the names of variable uses gui but equally well it could be cterm. As
" 	they work in gui and vim. 
    if has("gui_running")
	let notification_guibg = exists("g:atp_notification_".colors_name."_guibg") ?
		    \ g:atp_notification_{colors_name}_guibg :
		    \ ( synIDattr(synIDtrans(hlID("StatusLine")), "reverse") ?
			\ synIDattr(synIDtrans(hlID("StatusLine")), "fg#") :
			\ synIDattr(synIDtrans(hlID("StatusLine")), "bg#") )
	let notification_guifg = exists("g:atp_notification_".colors_name."_guifg") ?
		    \ g:atp_notification_{colors_name}_guifg :
		    \ ( synIDattr(synIDtrans(hlID("StatusLine")), "reverse") ?
			\ synIDattr(synIDtrans(hlID("StatusLine")), "bg#") :
			\ synIDattr(synIDtrans(hlID("StatusLine")), "fg#") )
	let notification_gui = exists("g:atp_notification_".colors_name."_gui") ?
		    \ g:atp_notification_{colors_name}_gui :
		    \ ( (synIDattr(synIDtrans(hlID("StatusLine")), "bold") ? "bold" : "" ) . 
			\ (synIDattr(synIDtrans(hlID("StatusLine")), "underline") ? ",underline" : "" ) .
			\ (synIDattr(synIDtrans(hlID("StatusLine")), "underculr") ? ",undercurl" : "" ) .
			\ (synIDattr(synIDtrans(hlID("StatusLine")), "italic") ? ",italic" : "" ) )
    else
	let notification_guibg = exists("g:atp_notification_".colors_name."_ctermbg") ?
		    \ g:atp_notification_{colors_name}_ctermbg :
		    \ ( synIDattr(synIDtrans(hlID("StatusLine")), "reverse") ?
			\ synIDattr(synIDtrans(hlID("StatusLine")), "fg#") :
			\ synIDattr(synIDtrans(hlID("StatusLine")), "bg#") )
	let notification_guifg = exists("g:atp_notification_".colors_name."_ctermfg") ?
		    \ g:atp_notification_{colors_name}_ctermfg :
		    \ ( synIDattr(synIDtrans(hlID("StatusLine")), "reverse") ?
			\ synIDattr(synIDtrans(hlID("StatusLine")), "bg#") :
			\ synIDattr(synIDtrans(hlID("StatusLine")), "fg#") )
	let notification_gui = exists("g:atp_notification_".colors_name."_cterm") ?
		    \ g:atp_notification_{colors_name}_cterm :
		    \ ( (synIDattr(synIDtrans(hlID("StatusLine")), "bold") ? "bold" : "" ) . 
			\ (synIDattr(synIDtrans(hlID("StatusLine")), "underline") ? ",underline" : "" ) .
			\ (synIDattr(synIDtrans(hlID("StatusLine")), "underculr") ? ",undercurl" : "" ) .
			\ (synIDattr(synIDtrans(hlID("StatusLine")), "italic") ? ",italic" : "" ) )
    endif

    if has("gui_running")
	let g:notification_gui		= notification_gui
	let g:notification_guibg	= notification_guibg
	let g:notification_guifg	= notification_guifg
    else
	let g:notification_cterm	= notification_gui
	let g:notification_ctermbg	= notification_guibg
	let g:notification_ctermfg	= notification_guifg
    endif
    if has("gui_running")
	let prefix = "gui"
    else
	let prefix = "cterm"
    endif
    let hi_gui	 = ( notification_gui   !=  "" && notification_gui   	!= -1 ? " ".prefix."="   . notification_gui   : "" )
    let hi_guifg = ( notification_guifg !=  "" && notification_guifg 	!= -1 ? " ".prefix."fg=" . notification_guifg : "" )
    let hi_guibg = ( notification_guibg !=  "" && notification_guibg 	!= -1 ? " ".prefix."bg=" . notification_guibg : "" )

    if (notification_gui == -1 || notification_guifg == -1 || notification_guibg == -1)
	return
    endif
    " Highlight command:
    try
    execute "hi User".g:atp_statusNotifHi ." ". hi_gui . hi_guifg . hi_guibg
    catch /E418:/
    endtry

endfunction
"}}}

" The main status function, it is called via autocommand defined in 'options.vim'.
let s:errormsg = 0
" a:command = 1/0: 1 if run by a command, then a:1=bang, a:2=ctoc, 
" if a:command = 0, then a:1=ctoc.
function! ATPStatus(command,...) "{{{
    if expand("%") == "[Command Line]" || &l:filetype == "qf" || expand("%:e") != "tex"
	" If one uses q/ or q? this status function should not be used.
	return
    endif

    if a:command >= 1
	" This is run be the command :Status (:ATPStatus)
	if a:0 >= 1 && a:1
	    let g:status_OutDir = s:StatusOutDir()
	    let g:atp_statusOutDir = 1
	else
	    let g:status_OutDir = ""
	    let g:atp_statusOutDir = 0
	endif
	let ctoc = ( a:0 >= 2 ? a:2 : 0 )
    else
	" This is run by the autocommand group ATP_Status
	if g:atp_statusOutDir
	    let g:status_OutDir = s:StatusOutDir()
	else
	    let g:status_OutDir = ""
	endif
	let ctoc = ( a:0 >= 1 ? a:1 : 0 )
    endif
    " There is a bug in CTOC() which prevents statusline option from being set right.
    " This is a dirty workaround:
"     silent echo CTOC("return")
    let status_CTOC	= ( ctoc && &l:filetype =~ '^\(ams\)\=tex' ? '%{CTOC("return")}' : '' )
    if g:atp_statusNotifHi > 9 || g:atp_statusNotifHi < 0
	let g:atp_statusNotifHi = 9
	if !s:errormsg
	    echoerr "Wrong value of g:atp_statusNotifHi, should be 0,1,...,9. Setting it to 9."
	    let s:errormsg = 1
	endif
    endif
    let status_NotifHi	=
		\ ( g:atp_statusNotif && g:atp_statusNotifHi 	? '%#User'.g:atp_statusNotifHi . '#' : '' )
    let status_NotifHiPost =
		\ ( g:atp_statusNotif && g:atp_statusNotifHi 	? '%*' 	: '' )
    let status_Notif	=
		\ ( g:atp_statusNotif 			? '%{ATPRunning()}' 	: '' )
    let status_KeyMap	=
		\ ( has("keymap") && g:atp_babel && exists("b:keymap_name") 	
								\ ? b:keymap_name 	: '' )
    let g:atp_StatusLine= '%<%f '.status_KeyMap.'%(%h%m%r%) '.status_NotifHi.status_Notif.status_NotifHiPost.'%= '.status_CTOC.' %{g:status_OutDir} %-14.16(%l,%c%V%)%P'
    set statusline=%!g:atp_StatusLine
endfunction
try
    command -buffer -bang Status	:call ATPStatus(1,(<q-bang> == "")) 
catch /E174:/
    command! -buffer -bang ATPStatus	:call ATPStatus(1,(<q-bang> == "!")) 
endtry
" }}}
"}}}
" The Script:
" (includes commands, and maps - all the things 
" 		that must be sources for each file
" 		+ sets g:atp_inputfile_pattern variable)
" {{{1
call atplib#common#SetProjectName()

" The pattern g:atp_inputfile_pattern should match till the begining of the file name
" and shouldn't use \zs:\ze. 
if !exists("g:atp_inputfile_pattern") || g:atp_reload_variables
    if &filetype == 'plaintex'
	let g:atp_inputfile_pattern = '^[^%]*\\input\>\s*'
    else
	if atplib#search#SearchPackage("subfiles")
	    let g:atp_inputfile_pattern = '^[^%]*\\\(input\s*{\=\|include\s*{\|subfile\s*{'
	else
	    let g:atp_inputfile_pattern = '^[^%]*\\\(input\s*{\=\|include\s*{'
	endif
	if atplib#search#SearchPackage("biblatex")
	    let g:atp_inputfile_pattern .= '\)'
	else
	    let g:atp_inputfile_pattern .= '\|bibliography\s*{\)'
	endif
    endif
endif


call atplib#common#SetOutDir(0, 1)
if expand("%:e") == "tex"
    " cls and sty files also have filetype 'tex', this prevents from setting the error
    " file for them.
    call atplib#common#SetErrorFile()
endif "}}}1

" Commands:
"{{{1
command! -buffer -bang SetProjectName	:call atplib#common#SetProjectName(<q-bang>, 0)
command! -buffer SetErrorFile		:call atplib#common#SetErrorFile()
command! -buffer SetOutDir		:call atplib#common#SetOutDir(1)
command! -buffer InputFiles 		:call atplib#search#UpdateMainFile() | :call atplib#search#FindInputFiles(atplib#FullPath(b:atp_MainFile)) | echo join([b:atp_MainFile]+b:ListOfFiles, "\n")

" This should set the variables and run atplib#common#SetNotificationColor function
command! -buffer SetNotificationColor :call atplib#common#SetNotificationColor()
augroup ATP_SetStatusLineNotificationColor
    au!
    au VimEnter 		*.tex 	:call s:SetNotificationColor()
    au BufEnter 		*.tex 	:call s:SetNotificationColor()
    au ColorScheme 		* 	:call s:SetNotificationColor()
augroup END
"}}}
" vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1
ftplugin/ATP_files/compile.py	[[[1
561
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Marcin Szamotulski <mszamot[@]gmail[.]com>
# This file is a part of Automatic TeX Plugin for Vim.

import sys, errno, os.path, shutil, subprocess, psutil, re, tempfile, optparse, glob
import traceback, atexit

from os import chdir, mkdir, putenv, devnull
from optparse import OptionParser
from collections import deque

import latex_log


# readlink is not available on Windows.
readlink=True
try:
    from os import readlink
except ImportError:
    readlink=False

####################################
#
#       Parse Options:   
#
####################################

usage   = "usage: %prog [options]"
parser  = OptionParser(usage=usage)

parser.add_option("--command",          dest="command",         default="pdflatex"                      )
parser.add_option("--bibcommand",       dest="bibcommand",      default="bibtex"                        )
parser.add_option("--progname",         dest="progname",        default="gvim"                          )
parser.add_option("--aucommand",        dest="aucommand",       default=False, action="store_true"      )
parser.add_option("--tex-options",      dest="tex_options",     default="-synctex=1,-interaction=nonstopmode")
parser.add_option("--verbose",          dest="verbose",         default="silent"                        )
parser.add_option("--file",             dest="mainfile",                                                )
parser.add_option("--bufnr",            dest="bufnr",                                                   )
parser.add_option("--output-format",    dest="output_format",   default="pdf"                           )
parser.add_option("--runs",             dest="runs",            default=1,             type="int"       )
parser.add_option("--no-callback",      dest="callback",        default=True,           action="store_false")
parser.add_option("--progressbar_file", dest="pb_fname",        default="",                             )
parser.add_option("--servername",       dest="servername",                                              )
parser.add_option("--start",            dest="start",           default=0,             type="int"       )
parser.add_option("--viewer",           dest="viewer",          default="xpdf"                          )
parser.add_option("--xpdf-server",      dest="xpdf_server",                                             )
parser.add_option("--viewer-options",   dest="viewer_opt",      default=""                              )
parser.add_option("--keep",             dest="keep",            default="aux,toc,bbl,ind,pdfsync,synctex.gz")
parser.add_option("--env",              dest="env",             default=""  )
parser.add_option("--logdir",           dest="logdir")
# Boolean switches:
parser.add_option("--reload-viewer",    action="store_true",    default=False,  dest="reload_viewer")
parser.add_option("--bibtex",           action="store_true",    default=False,  dest="bibtex"           )
parser.add_option("--reload-on-error",  action="store_true",    default=False,  dest="reload_on_error"  )
parser.add_option("--bang",             action="store_false",   default=False,  dest="bang"             )
parser.add_option("--gui-running",      action="store_true",    default=False,  dest="gui_running"      )
parser.add_option("--autex_wait",       action="store_true",    default=False,  dest="autex_wait"       )
parser.add_option("--no-progress-bar",  action="store_false",   default=True,   dest="progress_bar"     )
parser.add_option("--bibliographies",                           default="",     dest="bibliographies"   )
parser.add_option("--tempdir",                                  default="",     dest="tempdir"        )

(options, args) = parser.parse_args()

# Debug file should be changed for sth platform independent
# There should be a switch to get debug info.

def nonempty(string):
    if str(string) == '':
        return False
    else:
        return True

logdir          = options.logdir
script_logfile  = os.path.join(logdir, 'compile.log')
debug_file      = open(script_logfile, 'w')

# Cleanup on exit:
def cleanup(debug_file):
    debug_file.close()
    shutil.rmtree(tmpdir)
atexit.register(cleanup, debug_file)

command         = options.command
bibcommand      = options.bibcommand
progname        = options.progname
aucommand_bool  = options.aucommand
if aucommand_bool:
    aucommand="AU"
else:
    aucommand="COM"
command_opt     = list(filter(nonempty,re.split('\s*,\s*', options.tex_options)))
mainfile_fp     = options.mainfile
bufnr           = options.bufnr
output_format   = options.output_format
if output_format == "pdf":
    extension = ".pdf"
else:
    extension = ".dvi"
runs            = options.runs
servername      = options.servername
pb_fname        = options.pb_fname
start           = options.start
viewer          = options.viewer
autex_wait      = options.autex_wait
XpdfServer      = options.xpdf_server
viewer_rawopt   = re.split('\s*;\s*', options.viewer_opt)
viewer_it       = list(filter(nonempty,viewer_rawopt))
viewer_opt      =[]
for opt in viewer_it:
    viewer_opt.append(opt)
viewer_rawopt   = viewer_opt
if viewer == "xpdf" and XpdfServer != None:
    viewer_opt.extend(["-remote", XpdfServer])
verbose         = options.verbose
keep            = options.keep.split(',')
keep            = list(filter(nonempty, keep))

env             = list(map(lambda x: re.split('\s*=\s*', x), list(filter(nonempty, re.split('\s*;\s*',options.env)))))

# Boolean options
reload_viewer   = options.reload_viewer
bibtex          = options.bibtex
bibliographies  = options.bibliographies.split(",")
bibliographies  = list(filter(nonempty, bibliographies))
bang            = options.bang
reload_on_error = options.reload_on_error
gui_running     = options.gui_running
progress_bar    = options.progress_bar

debug_file.write("COMMAND "+command+"\n")
debug_file.write("BIBCOMMAND "+bibcommand+"\n")
debug_file.write("AUCOMMAND "+aucommand+"\n")
debug_file.write("PROGNAME "+progname+"\n")
debug_file.write("COMMAND_OPT "+str(command_opt)+"\n")
debug_file.write("MAINFILE_FP "+str(mainfile_fp)+"\n")
debug_file.write("OUTPUT FORMAT "+str(output_format)+"\n")
debug_file.write("EXT "+extension+"\n")
debug_file.write("RUNS "+str(runs)+"\n")
debug_file.write("VIM_SERVERNAME "+str(servername)+"\n")
debug_file.write("START "+str(start)+"\n")
debug_file.write("VIEWER "+str(viewer)+"\n")
debug_file.write("XPDF_SERVER "+str(XpdfServer)+"\n")
debug_file.write("VIEWER_OPT "+str(viewer_opt)+"\n")
debug_file.write("DEBUG MODE (verbose) "+str(verbose)+"\n")
debug_file.write("KEEP "+str(keep)+"\n")
debug_file.write("BIBLIOGRAPHIES "+str(bibliographies)+"\n")
debug_file.write("ENV OPTION "+str(options.env)+"\n")
debug_file.write("ENV "+str(env)+"\n")
debug_file.write("*BIBTEX "+str(bibtex)+"\n")
debug_file.write("*BANG "+str(bang)+"\n")
debug_file.write("*RELOAD_VIEWER "+str(reload_viewer)+"\n")
debug_file.write("*RELOAD_ON_ERROR "+str(reload_on_error)+"\n")
debug_file.write("*GUI_RUNNING "+str(gui_running)+"\n")
debug_file.write("*PROGRESS_BAR "+str(progress_bar)+"\n")

####################################
#
#       Functions:   
#
####################################

def decode_list(byte):
    return byte.decode()

def write_pbf(string):
    # Open pb_fname and write nr to it 
    # only if int(string) is greater than what is in this file 

    cond = False
    try:
        if sys.version_info < (3, 0):
            pb_fobject  = open(pb_fname, 'r')
        else:
            pb_fobject  = open(pb_fname, 'r', errors='replace')
    except IOError:
        debug_file.write("write_pbf at line %d: %s" % (sys.exc_info()[2].tb_lineno, str(ioerror)))
        cond = True
    else:
        pb_file     = pb_fobject.read()
    finally:
        pb_fobject.close()
    if not cond:
        pb          = re.match('(\d*)', pb_file)
        pb_fobject.close()
        if pb:
            try:
                nr = int(pb.group(1))
            except ValueError:
                nr = -1
        else:
            nr = 0
        try:
            if nr >= 0:
                cond = int(string) > nr
            else:
                cond = True
        except ValueError:
            cond = False
            pass
    if cond:
        try:
            pb_fobject=open(pb_fname, 'w')
        except IOError as ioerror:
            debug_file.write("write_pbf at line %d: %s" % (sys.exc_info()[2].tb_lineno, str(ioerror)))
            pass
        else:
            pb_fobject.write(string+"\n")
        finally:
            pb_fobject.close()

def latex_progress_bar(cmd):
    # Run latex and send data for progress bar,

    child = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    pid   = child.pid
    vim_remote_expr(servername, "atplib#callback#LatexPID("+str(pid)+")")
    debug_file.write("latex pid "+str(pid)+"\n")
    stack = deque([])
    while True:
        try:
            out = child.stdout.read(1).decode(errors="replace")
        except UnicodeDecodeError:
            debug_file.write("UNICODE DECODE ERROR:\n")
            debug_file.write(child.stdout.read(1).encode(errors="ignore"))
            debug_file.write("\n")
            debug_file.write("stack="+''.join(stack)+"\n")
            out = ""
        if out == '' and child.poll() != None:
            break
        if out != '':
            stack.append(out)
            if len(stack)>10:
                stack.popleft()
            match = re.match('\[(\n?\d(\n|\d)*)({|\])',''.join(stack))
            if match:
                if options.callback:
                    vim_remote_expr(servername, "atplib#callback#ProgressBar("+match.group(1)[match.start():match.end()]+","+str(pid)+","+str(bufnr)+")")
                else:
                    write_pbf(match.group(1)[match.start():match.end()])
    child.wait()
    vim_remote_expr(servername, "atplib#callback#ProgressBar('end',"+str(pid)+","+str(bufnr)+")")
    vim_remote_expr(servername, "atplib#callback#PIDsRunning(\"b:atp_LatexPIDs\")")
    if not options.callback:
        try:
            pb_fobject = open(pb_fname, 'w')
        except IOError as ioerror:
            debug_file.write("latex_progress_bar at line %d : %s" % (sys.exc_info()[2].tb_lineno, str(ioerror)))
            pass
        else:
            pb_fobject.write('')
        finally:
            pb_fobject.close()
    return child

def xpdf_server_file_dict():
    # Make dictionary of the type { xpdf_servername : [ file, xpdf_pid ] },

    # to test if the server host file use:
    # basename(xpdf_server_file_dict().get(server, ['_no_file_'])[0]) == basename(file)
    # this dictionary always contains the full path (Linux).
    # TODO: this is not working as I want to:
    #    when the xpdf was opened first without a file it is not visible in the command line
    #    I can use 'xpdf -remote <server> -exec "run('echo %f')"'
    #    where get_filename is a simple program which returns the filename. 
    #    Then if the file matches I can just reload, if not I can use:
    #          xpdf -remote <server> -exec "openFile(file)"
    ps_list=psutil.get_pid_list()
    server_file_dict={}
    for pr in ps_list:
        try:
            name=psutil.Process(pr).name
            cmdline=psutil.Process(pr).cmdline
            if name == 'xpdf':
                try:
                    ind=cmdline.index('-remote')
                except:
                    ind=0
                if ind != 0 and len(cmdline) >= 1:
                    server_file_dict[cmdline[ind+1]]=[cmdline[len(cmdline)-1], pr]
        except psutil.error.NoSuchProcess:
            pass
        except psutil.error.AccessDenied:
            pass
    return server_file_dict

def vim_remote_expr(servername, expr):
    # Send <expr> to vim server,

    # expr must be well quoted:
    #       vim_remote_expr('GVIM', "atplib#callback#TexReturnCode()")
    if not options.callback:
        return
    cmd=[progname, '--servername', servername, '--remote-expr', expr]
    child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE).wait()


####################################
#
#       Arguments:   
#
####################################

# If mainfile_fp is not a full path make it. 
glob=glob.glob(os.path.join(os.getcwd(),mainfile_fp))
if len(glob) != 0:
    mainfile_fp = glob[0]
mainfile        = os.path.basename(mainfile_fp)
mainfile_dir    = os.path.dirname(mainfile_fp)
if mainfile_dir == "":
    mainfile_fp = os.path.join(os.getcwd(), mainfile)
    mainfile    = os.path.basename(mainfile_fp)
    mainfile_dir= os.path.dirname(mainfile_fp)
if options.tempdir == "":
    options.tempdir = os.path.join(mainfile_dir,".tmp")
if os.path.islink(mainfile_fp):
    if readlink:
        mainfile_fp = os.readlink(mainfile_fp)
    # The above line works if the symlink was created with full path. 
    mainfile    = os.path.basename(mainfile_fp)
    mainfile_dir= os.path.dirname(mainfile_fp)

mainfile_dir    = os.path.normcase(mainfile_dir)
[basename, ext] = os.path.splitext(mainfile)
output_fp       = os.path.splitext(mainfile_fp)[0]+extension

try:
    # Send pid to ATP:
    if verbose != "verbose":
        vim_remote_expr(servername, "atplib#callback#PythonPID("+str(os.getpid())+")")
    ####################################
    #
    #       Make temporary directory,
    #       Copy files and Set Environment:
    #
    ####################################
    cwd     = os.getcwd()
    if not os.path.exists(options.tempdir):
        # This is the main tmp dir (./.tmp) 
        # it will not be deleted by this script
        # as another instance might be using it.
        # it is removed by Vim on exit.
        os.mkdir(options.tempdir)
    tmpdir  = tempfile.mkdtemp(dir=options.tempdir,prefix="")
    debug_file.write("TMPDIR: "+tmpdir+"\n")
    tmpaux  = os.path.join(tmpdir,basename+".aux")

    command_opt.append('-output-directory='+tmpdir)
    latex_cmd      = [command]+command_opt+[mainfile_fp]
    debug_file.write("COMMAND "+str(latex_cmd)+"\n")
    debug_file.write("COMMAND "+" ".join(latex_cmd)+"\n")

    # Copy important files to output directory:
    # /except the log file/
    os.chdir(mainfile_dir)
    for ext in filter(lambda x: x != "log", keep):
        file_cp=basename+"."+ext
        if os.path.exists(file_cp):
            shutil.copy(file_cp, tmpdir)

    tempdir_list = os.listdir(tmpdir)
    debug_file.write("\nls tmpdir "+str(tempdir_list)+"\n")

    # Set environment
    for var in env:
        debug_file.write("ENV "+var[0]+"="+var[1]+"\n")
        os.putenv(var[0], var[1])

    # Link local bibliographies:
    for bib in bibliographies:
        if os.path.exists(os.path.join(mainfile_dir,os.path.basename(bib))):
            os.symlink(os.path.join(mainfile_dir,os.path.basename(bib)),os.path.join(tmpdir,os.path.basename(bib)))

    ####################################
    #
    #       Compile:   
    #
    ####################################
    # Start Xpdf (this can be done before compelation, because we can load file
    # into afterwards) in this way Xpdf starts faster (it is already running when
    # file compiles). 
    # TODO: this might cause problems when the tex file is very simple and short.
    # Can we test if xpdf started properly?  okular doesn't behave nicely even with
    # --unique switch.

    # Latex might not run this might happen with bibtex (?)
    latex_returncode=0
    if bibtex and os.path.exists(tmpaux):
        if bibcommand == 'biber':
            bibfname = basename
        else:
            bibfname = basename+".aux"
        debug_file.write("\nBIBTEX1"+str([bibcommand, bibfname])+"\n")
        os.chdir(tmpdir)
        bibtex_popen=subprocess.Popen([bibcommand, bibfname], stdout=subprocess.PIPE)
        vim_remote_expr(servername, "atplib#callback#BibtexPID('"+str(bibtex_popen.pid)+"')")
        vim_remote_expr(servername, "atplib#callback#redrawstatus()")
        bibtex_popen.wait()
        vim_remote_expr(servername, "atplib#callback#PIDsRunning(\"b:atp_BibtexPIDs\")")
        os.chdir(mainfile_dir)
        bibtex_returncode=bibtex_popen.returncode
        bibtex_output=re.sub('"', '\\"', bibtex_popen.stdout.read())
        debug_file.write("BIBTEX RET CODE "+str(bibtex_returncode)+"\nBIBTEX OUTPUT\n"+bibtex_output+"\n")
        if verbose != 'verbose':
            vim_remote_expr(servername, "atplib#callback#BibtexReturnCode('"+str(bibtex_returncode)+"',\""+str(bibtex_output)+"\")")
        else:
            print(bibtex_output)
        # We need run latex at least 2 times
        bibtex=False
        runs=max([runs, 2])
    elif bibtex:
        # we need run latex at least 3 times
        runs=max([runs, 3])

    debug_file.write("\nRANGE="+str(range(1,int(runs+1)))+"\n")
    debug_file.write("RUNS="+str(runs)+"\n")
    for i in range(1, int(runs+1)):
        debug_file.write("RUN="+str(i)+"\n")
        debug_file.write("DIR="+str(os.getcwd())+"\n")
        tempdir_list = os.listdir(tmpdir)
        debug_file.write("ls tmpdir "+str(tempdir_list)+"\n")
        debug_file.write("BIBTEX="+str(bibtex)+"\n")

        if verbose == 'verbose' and i == runs:
            debug_file.write("VERBOSE"+"\n")
            latex=subprocess.Popen(latex_cmd)
            pid=latex.pid
            debug_file.write("latex pid "+str(pid)+"\n")
            latex.wait()
            latex_returncode=latex.returncode
            debug_file.write("latex ret code "+str(latex_returncode)+"\n")
        else:
            if progress_bar and verbose != 'verbose':
                latex=latex_progress_bar(latex_cmd)
            else:
                latex = subprocess.Popen(latex_cmd, stdout=subprocess.PIPE)
                pid   = latex.pid
                vim_remote_expr(servername, "atplib#callback#LatexPID("+str(pid)+")")
                debug_file.write("latex pid "+str(pid)+"\n")
                latex.wait()
                vim_remote_expr(servername, "atplib#callback#PIDsRunning(\"b:atp_LatexPIDs\")")
            latex_returncode=latex.returncode
            debug_file.write("latex return code "+str(latex_returncode)+"\n")
            tempdir_list = os.listdir(tmpdir)
            debug_file.write("JUST AFTER LATEX ls tmpdir ("+str(tmpdir)+") "+str(tempdir_list)+"\n")
        # Return code of compilation:
        if verbose != "verbose":
            vim_remote_expr(servername, "atplib#callback#TexReturnCode('"+str(latex_returncode)+"')")
        if bibtex and i == 1:
            if bibcommand == 'biber':
                bibfname = basename
            else:
                bibfname = basename+".aux"
            debug_file.write("BIBTEX2 "+str([bibcommand, bibfname])+"\n")
            debug_file.write(os.getcwd()+"\n")
            tempdir_list = os.listdir(tmpdir)
            debug_file.write("ls tmpdir "+str(tempdir_list)+"\n")
            os.chdir(tmpdir)
            bibtex_popen=subprocess.Popen([bibcommand, bibfname], stdout=subprocess.PIPE)
            vim_remote_expr(servername, "atplib#callback#BibtexPID('"+str(bibtex_popen.pid)+"')")
            vim_remote_expr(servername, "atplib#callback#redrawstatus()")
            bibtex_popen.wait()
            vim_remote_expr(servername, "atplib#callback#PIDsRunning(\"b:atp_BibtexPIDs\")")
            os.chdir(mainfile_dir)
            bibtex_returncode=bibtex_popen.returncode
            bibtex_output=re.sub('"', '\\"', bibtex_popen.stdout.read())
            debug_file.write("BIBTEX2 RET CODE"+str(bibtex_returncode)+"\n")
            if verbose != 'verbose':
                vim_remote_expr(servername, "atplib#callback#BibtexReturnCode('"+str(bibtex_returncode)+"',\""+str(bibtex_output)+"\")")
            else:
                print(bibtex_output)

    ####################################
    #
    #       Copy Files:
    #
    ####################################

    # Copy files:
    os.chdir(tmpdir)
    for ext in list(filter(lambda x: x != 'aux', keep))+[output_format]:
        file_cp=basename+"."+ext
        if os.path.exists(file_cp):
            debug_file.write(file_cp+' \n')
            shutil.copy(file_cp, mainfile_dir)

    # Copy aux file if there were no compilation errors or if it doesn't exists in mainfile_dir.
    # copy aux file to _aux file (for atplib#tools#GrepAuxFile)
    if latex_returncode == 0 or not os.path.exists(os.path.join(mainfile_dir, basename+".aux")):
        file_cp=basename+".aux"
        if os.path.exists(file_cp):
            shutil.copy(file_cp, mainfile_dir)
    file_cp=basename+".aux"
    if os.path.exists(file_cp):
        shutil.copy(file_cp, os.path.join(mainfile_dir, basename+"._aux"))
    os.chdir(cwd)

    ####################################
    #
    #       Call Back Communication:   
    #
    ####################################
    if verbose != "verbose":
        debug_file.write("CALL BACK "+"atplib#callback#CallBack('"+str(bufnr)+"','"+str(verbose)+"','"+aucommand+"','"+str(options.bibtex)+"')"+"\n")
        vim_remote_expr(servername, "atplib#callback#CallBack('"+str(bufnr)+"','"+str(verbose)+"','"+aucommand+"','"+str(options.bibtex)+"')")
        # return code of compelation is returned before (after each compilation).


    ####################################
    #
    #       Reload/Start Viewer:   
    #
    ####################################
    if re.search(viewer, '^\s*xpdf\e') and reload_viewer:
        # The condition tests if the server XpdfServer is running
        xpdf_server_dict=xpdf_server_file_dict()
        cond = xpdf_server_dict.get(XpdfServer, ['_no_file_']) != ['_no_file_']
        debug_file.write("XPDF SERVER DICT="+str(xpdf_server_dict)+"\n")
        debug_file.write("COND="+str(cond)+":"+str(reload_on_error)+":"+str(bang)+"\n")
        debug_file.write("COND="+str( not reload_on_error or bang )+"\n")
        debug_file.write(str(xpdf_server_dict)+"\n")
        if start == 1:
            run=['xpdf']
            run.extend(viewer_opt)
            run.append(output_fp)
            debug_file.write("D1: "+str(run)+"\n")
            viewer_s=subprocess.Popen(run)
            # We cannot read stderr, since if there is no error it will freeze the script.
        elif cond and ( reload_on_error or latex_returncode == 0 or bang ):
            run=['xpdf', '-remote', XpdfServer, '-reload']
            viewer_s=subprocess.Popen(run)
            debug_file.write("D2: "+str(['xpdf',  '-remote', XpdfServer, '-reload'])+"\n")
    else:
        if start >= 1:
            run=[viewer]
            run.extend(viewer_opt)
            run.append(output_fp)
            print(run)
            debug_file.write("RUN "+str(run)+"\n")
            subprocess.Popen(run, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        if start == 2:
            vim_remote_expr(servername, "atplib#SyncTex()")

    # Rewrite LaTeX log file
    latex_log.rewrite_log(os.path.splitext(mainfile_fp)[0]+".log", check_path=True, project_dir=mainfile_dir, project_tmpdir=tmpdir)

####################################
#
#       Clean:
#
####################################
except Exception:
    latex_returncode = 0
    error_str=re.sub("'", "''",re.sub('"', '\\"', traceback.format_exc()))
    traceback.print_exc(None, debug_file)
    if options.callback:
        vim_remote_expr(servername, "atplib#callback#Echo(\"[ATP:] error in compile.py, catched python exception:\n"+error_str+"[ATP info:] this error message is recorded in compile.py.log under g:atp_TempDir\",'echo','ErrorMsg')")
    else:
        print(error_str)

sys.exit(latex_returncode)
ftplugin/ATP_files/compiler.vim	[[[1
94
" Author: 	Marcin Szamotulski	
" Note:		this file contain the main compiler function and related tools, to
" 		view the output, see error file.
" Note:		This file is a part of Automatic Tex Plugin for Vim.
" Language:	tex


if !filereadable("makefile") && !filereadable("Makefile")
    let s:makeprg=g:atp_Python." ".split(globpath(&rtp, "ftplugin/ATP_files/makelatex.py"), "\n")[0].
		\ " --texfile ".shellescape(atplib#FullPath(b:atp_MainFile)).
		\ " --bufnr ".bufnr("%").
		\ " --start 0".
		\ " --output-format ".substitute(get(g:atp_CompilersDict, matchstr(b:atp_TexCompiler, '^\s*\zs\S\+\ze'), ".pdf"), '\.', '', '').
		\ " --verbose ".t:atp_DebugMode.
		\ " --cmd ".b:atp_TexCompiler.
		\ " --bibcmd ".b:atp_BibCompiler.
		\ " --bibliographies ".shellescape(join(keys(filter(copy(b:TypeDict), "v:val == 'bib'")), ',')).
		\ " --outdir ".shellescape(b:atp_OutDir).
		\ " --keep ". shellescape(join(g:atp_keep, ',')).
		\ " --tex-options ".shellescape(b:atp_TexOptions.',-interaction='.( t:atp_DebugMode=="verbose" ? b:atp_VerboseLatexInteractionMode : 'nonstopmode' )).
		\ " --servername ".v:servername.
		\ " --viewer ".shellescape(b:atp_Viewer).
		\ " --xpdf-server ".shellescape(b:atp_XpdfServer).
		\ " --viewer-options ".shellescape((join((exists("g:atp_".matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')."Options") ? g:atp_{matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')}Options : []), ";") != "" ? join((exists("g:atp_".matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')."Options") ? g:atp_{matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')}Options : []), ";").";".join((exists("b:atp_".matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')."Options") ? getbufvar(bufnr("%"), "atp_".matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')."Options") : []), ";") : join((exists("b:atp_".matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')."Options") ? getbufvar(bufnr("%"), "atp_".matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')."Options") : []), ";"))).
		\ " --progname ".v:progname.
		\ " --tempdir ".shellescape(g:atp_TempDir).
		\ (g:atp_callback ? "" : " --no-callback ").
		\ (t:atp_DebugMode=='verbose' ? ' --env ""': " --env ".shellescape(b:atp_TexCompilerVariable)).
		\ ( index(g:atp_ReloadViewers, b:atp_Viewer)+1  ? ' --reload-viewer ' : '' ) . ( b:atp_ReloadOnError ? ' --reload-on-error ' : '' ).
		\ " &"

    let &l:makeprg = s:makeprg
endif
" Maps:
"{{{
noremap <silent> <Plug>ATP_ViewOutput_sync		:call atplib#compiler#ViewOutput("!", b:atp_MainFile, b:atp_XpdfServer)<CR>
noremap <silent> <Plug>ATP_ViewOutput_nosync		:call atplib#compiler#ViewOutput("",  b:atp_MainFile, b:atp_XpdfServer)<CR>
noremap <silent> <Plug>ATP_ViewLocalOutput_sync		:call atplib#compiler#ViewOutput("!", expand("%:p"), b:atp_LocalXpdfServer)<CR>
noremap <silent> <Plug>ATP_ViewLocalOutput_nosync	:call atplib#compiler#ViewOutput("",  expand("%:p"), b:atp_LocalXpdfServer)<CR>
nmap <buffer> <Plug>SyncTexKeyStroke	:call atplib#compiler#SyncTex("", 0, b:atp_MainFile, b:atp_XpdfServer)<CR>
nmap <buffer> <Plug>SyncTexMouse	:call atplib#compiler#SyncTex("", 1, b:atp_MainFile, b:atp_XpdfServer)<CR>
nmap <buffer> <Plug>SyncTexLKeyStroke	:call atplib#compiler#SyncTex("", 0, expand("%:t"), b:atp_LocalXpdfServer)<CR>
nmap <buffer> <Plug>SyncTexLMouse	:call atplib#compiler#SyncTex("", 1, expand("%:t"), b:atp_LocalXpdfServer)<CR>
noremap <silent> <Plug>ATP_TeXCurrent	:<C-U>call atplib#compiler#TeX(v:count1, "", t:atp_DebugMode)<CR>
noremap <silent> <Plug>ATP_TeXLocal	:<C-U>call atplib#compiler#LocalCompiler("n", "silent")<CR>
noremap <silent> <Plug>ATP_TeXDefault	:<C-U>call atplib#compiler#TeX(v:count1, "", 'default')<CR>
noremap <silent> <Plug>ATP_TeXSilent	:<C-U>call atplib#compiler#TeX(v:count1, "", 'silent')<CR>
noremap <silent> <Plug>ATP_TeXDebug	:<C-U>call atplib#compiler#TeX(v:count1, "", 'Debug')<CR>
noremap <silent> <Plug>ATP_TeXdebug	:<C-U>call atplib#compiler#TeX(v:count1, "", 'debug')<CR>
noremap <silent> <Plug>ATP_TeXVerbose	:<C-U>call atplib#compiler#TeX(v:count1, "", 'verbose')<CR>
inoremap <silent> <Plug>iATP_TeXVerbose	<Esc>:<C-U>call atplib#compiler#TeX(v:count1, "", 'verbose')<CR>
nnoremap <silent> <Plug>SimpleBibtex	:call atplib#compiler#SimpleBibtex()<CR>
nnoremap <silent> <Plug>SimpleBibtex	:call atplib#compiler#Bibtex("")<CR>
nnoremap <silent> <Plug>BibtexDefault	:call atplib#compiler#Bibtex("!", "default")<CR>
nnoremap <silent> <Plug>BibtexSilent	:call atplib#compiler#Bibtex("!", "silent")<CR>
nnoremap <silent> <Plug>Bibtexdebug	:call atplib#compiler#Bibtex("!", "debug")<CR>
nnoremap <silent> <Plug>BibtexDebug	:call atplib#compiler#Bibtex("!", "Debug")<CR>
nnoremap <silent> <Plug>BibtexVerbose	:call atplib#compiler#Bibtex("!", "verbose")<CR>
"}}}
" Commands And Autocommands: 
" {{{
if !has("patch468")
    command! 	 		Cgetfile		:cgetfile<bar>call atplib#compiler#FilterQuickFix()
endif
command! -buffer		HighlightErrors		:call atplib#callback#HighlightErrors()
command! -buffer		ClearHighlightErrors	:call atplib#callback#ClearHighlightErrors()
command! -buffer -bang 		Kill			:call atplib#compiler#Kill(<q-bang>)
command! -buffer -bang  	View			:call atplib#compiler#ViewOutput(<q-bang>, b:atp_MainFile, b:atp_XpdfServer)
command! -buffer -bang  	ViewL			:call atplib#compiler#ViewOutput(<q-bang>, expand("%:p"), b:atp_LocalXpdfServer)
command! -buffer -bang 		SyncTex			:call atplib#compiler#SyncTex(<q-bang>, 0, b:atp_MainFile, b:atp_XpdfServer)
command! -buffer -bang 		SyncTexL		:call atplib#compiler#SyncTex(<q-bang>, 0, expand("%"), b:atp_LocalXpdfServer)
command! -buffer 		PID			:call atplib#compiler#GetPID()
command! -buffer -nargs=? -bang -complete=custom,atplib#compiler#DebugComp MakeLatex	:call atplib#compiler#SetBiberSettings() | call atplib#compiler#MakeLatex(<q-bang>, <q-args>, 0)
nmap <buffer> <Plug>ATP_MakeLatex			:MakeLatex<CR>
command! -buffer -nargs=? -bang -count=1 -complete=custom,atplib#compiler#DebugComp TEX	:call atplib#compiler#TeX(<count>, <q-bang>, <f-args>)
command! -buffer -nargs=? -complete=custom,atplib#compiler#DebugComp TEXL 		:call atplib#compiler#LocalCompiler("n", <f-args>)
command! -buffer -count=1 DTEX				:call atplib#compiler#TeX(<count>, <q-bang>, 'debug') 
command! -buffer -bang -nargs=? -complete=custom,atplib#compiler#BibtexComp Bibtex		:call atplib#compiler#Bibtex(<q-bang>, <f-args>)
" command! -buffer BibtexOutput	:echo b:atp_BibtexOutput
" command! -buffer MakeidxOutput 	:echo b:atp_MakeidxOutput
command! -buffer -nargs=? -complete=custom,atplib#compiler#ListErrorsFlags_A SetErrorFormat 	:call atplib#compiler#SetErrorFormat(1,<f-args>)

augroup ATP_QuickFix_Commands
    au!
    au FileType qf command! -buffer -nargs=? -complete=custom,atplib#compiler#ListErrorsFlags_A SetErrorFormat :call atplib#compiler#SetErrorFormat(1,<q-args>)
    au FileType qf command! -buffer -nargs=? -complete=custom,atplib#compiler#ListErrorsFlags_A ErrorFormat :call atplib#compiler#SetErrorFormat(1,<q-args>)
    au FileType qf command! -buffer -nargs=? -complete=custom,atplib#compiler#ListErrorsFlags_A ShowErrors :call atplib#compiler#SetErrorFormat(0,<f-args>)
augroup END

command! -buffer -nargs=? -complete=custom,atplib#compiler#ListErrorsFlags_A 	ErrorFormat 	:call atplib#compiler#SetErrorFormat(1,<q-args>)
let load_ef=(exists("t:atp_QuickFixOpen") ? !t:atp_QuickFixOpen : 1)
command! -buffer -nargs=? -complete=custom,atplib#compiler#ListErrorsFlags 	ShowErrors 	:call atplib#compiler#ShowErrors(<f-args>)
" }}}
" vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1
ftplugin/ATP_files/complete.vim	[[[1
722
" Author: 	Marcin Szamotulski	
" Description: 	This file contains all the options and functions for completion.
" Note:		This file is a part of Automatic Tex Plugin for Vim.
" Language:	tex
" Last Change: Sat Mar 03, 2012 at 15:58:17  +0000

" Todo: biblatex.sty (recursive search for commands contains strange command \i}.

" TABCOMPLETION VARIABLES:
" {{{ TAB COMPLETION variables
" ( functions are in autoload/atplib.vim )

try 
let g:atp_completion_modes=[ 
	    \ 'commands', 		'labels', 		
	    \ 'tikz libraries', 	'environment names',
	    \ 'close environments' , 	'brackets',
	    \ 'input files',		'bibstyles',
	    \ 'bibitems', 		'bibfiles',
	    \ 'documentclass',		'tikzpicture commands',
	    \ 'tikzpicture',		'tikzpicture keywords',
	    \ 'package names',		'font encoding',
	    \ 'font family',		'font series',
	    \ 'font shape',		'algorithmic',
	    \ 'todonotes',
	    \ 'siunits',		'includegraphics',
	    \ 'color names',		'page styles',
	    \ 'page numberings',	'abbreviations',
	    \ 'package options', 	'documentclass options',
	    \ 'package options values', 'environment options',
	    \ 'command values'
	    \ ]
lockvar 2 g:atp_completion_modes
catch /E741:/
endtry

if !exists("g:atp_completion_modes_normal_mode")
    unlockvar g:atp_completion_modes_normal_mode
    let g:atp_completion_modes_normal_mode=[ 
		\ 'close environments' , 'brackets', 'algorithmic' ]
    lockvar g:atp_completion_modes_normal_mode
endif

" By defualt all completion modes are ative.
if !exists("g:atp_completion_active_modes")
    let g:atp_completion_active_modes=deepcopy(g:atp_completion_modes)
"     call filter(g:atp_completion_active_modes, "v:val != 'tikzpicture keywords'")
endif
if !exists("g:atp_completion_active_modes_normal_mode")
    let g:atp_completion_active_modes_normal_mode=deepcopy(g:atp_completion_modes_normal_mode)
endif

if !exists("g:atp_sort_completion_list")
    let g:atp_sort_completion_list = 12
endif

" Note: to remove completions: 'inline_math' or 'displayed_math' one has to
" remove also: 'close_environments' /the function atplib#complete#CloseLastEnvironment can
" close math instead of an environment/.

" ToDo: make list of complition commands from the input files.
" ToDo: make complition fot \cite, and for \ref and \eqref commands.

" ToDo: there is second such a list! line 3150
	let g:atp_Environments=['array', 'abstract', 'center', 'corollary', 
		\ 'definition', 'document', 'description', 'displaymath',
		\ 'enumerate', 'example', 'eqnarray', 
		\ 'flushright', 'flushleft', 'figure', 'frontmatter', 
		\ 'keywords', 
		\ 'itemize', 'lemma', 'list', 'letter', 'notation', 'minipage', 
		\ 'proof', 'proposition', 'picture', 'theorem', 'tikzpicture',  
		\ 'tabular', 'table', 'tabbing', 'thebibliography', 'titlepage',
		\ 'quotation', 'quote',
		\ 'remark', 'verbatim', 'verse', 'frame' ]

	let g:atp_amsmath_environments=['align', 'alignat', 'equation', 'gather',
		\ 'multline', 'split', 'substack', 'flalign', 'smallmatrix', 'subeqations',
		\ 'pmatrix', 'bmatrix', 'Bmatrix', 'vmatrix' ]

	" if short name is no_short_name or '' then both means to do not put
	" anything, also if there is no key it will not get a short name.
	let g:atp_shortname_dict = { 'theorem' : 'thm', 
		    \ 'proposition' 	: 'prop', 	'definition' 	: 'defi',
		    \ 'lemma' 		: 'lem',	'array' 	: 'ar',
		    \ 'abstract' 	: 'no_short_name',
		    \ 'tikzpicture' 	: 'tikz',	'tabular' 	: 'table',
		    \ 'table' 		: 'table', 	'proof' 	: 'pr',
		    \ 'corollary' 	: 'cor',	'enumerate' 	: 'enum',
		    \ 'example' 	: 'ex',		'itemize' 	: 'it',
		    \ 'item'		: 'itm',	'algorithmic'	: 'alg',
		    \ 'algorithm'	: 'alg',
		    \ 'remark' 		: 'rem',	'notation' 	: 'not',
		    \ 'center' 		: '', 		'flushright' 	: '',
		    \ 'flushleft' 	: '', 		'quotation' 	: 'quot',
		    \ 'quot' 		: 'quot',	'tabbing' 	: '',
		    \ 'picture' 	: 'pic',	'minipage' 	: '',	
		    \ 'list' 		: 'list',	'figure' 	: 'fig',
		    \ 'verbatim' 	: 'verb', 	'verse' 	: 'verse',
		    \ 'thebibliography' : '',		'document' 	: 'no_short_name',
		    \ 'titlepave' 	: '', 		'align' 	: 'eq',
		    \ 'alignat' 	: 'eq',		'equation' 	: 'eq',
		    \ 'gather'  	: 'eq', 	'multline' 	: 'eq',
		    \ 'split'		: 'eq', 	'substack' 	: '',
		    \ 'flalign' 	: 'eq',		'displaymath' 	: 'eq',
		    \ 'part'		: 'prt',	'chapter' 	: 'chap',
		    \ 'section' 	: 'sec',	'subsection' 	: 'ssec',
		    \ 'subsubsection' 	: 'sssec', 	'paragraph' 	: 'par',
		    \ 'subparagraph' 	: 'spar',	'subequations'	: 'eq' }

	" ToDo: Doc.
	" Usage: \label{l:shorn_env_name . g:atp_separator
	if !exists("g:atp_separator")
	    let g:atp_separator=':'
	endif
	if !exists("g:atp_no_separator")
	    let g:atp_no_separator = 0
	endif
" 	if !g:atp_no_separator
" 	    " This sets iskeyword vim option (see syntax/tex.vim file)
" 	    let g:tex_isk ="48-57,_,@,a-z,A-Z,192-255,".g:atp_separator
" 	endif
	if !exists("g:atp_no_short_names")
	    let g:atp_env_short_names = 1
	endif
	" the separator will not be put after the environments in this list:  
	" the empty string is on purpose: to not put separator when there is
	" no name.
	let g:atp_no_separator_list=['', 'titlepage']

" 	let g:atp_package_list=sort(['amsmath', 'amssymb', 'amsthm', 'amstex', 
" 	\ 'babel', 'booktabs', 'bookman', 'color', 'colorx', 'chancery', 'charter', 'courier',
" 	\ 'enumerate', 'euro', 'fancyhdr', 'fancyheadings', 'fontinst', 
" 	\ 'geometry', 'graphicx', 'graphics',
" 	\ 'hyperref', 'helvet', 'layout', 'longtable',
" 	\ 'newcent', 'nicefrac', 'ntheorem', 'palatino', 'stmaryrd', 'showkeys', 'tikz',
" 	\ 'qpalatin', 'qbookman', 'qcourier', 'qswiss', 'qtimes', 'verbatim', 'wasysym'])

	" the command \label is added at the end.
	let g:atp_Commands=["\\begin{", "\\end{", 
	\ "\\cite", "\\nocite{", "\\ref{", "\\pageref{", "\\eqref{", "\\item",
	\ "\\emph{", "\\documentclass{", "\\usepackage{",
	\ "\\section", "\\subsection", "\\subsubsection", "\\part", 
	\ "\\appendix", "\\subparagraph", "\\paragraph",
	\ "\\textbf{", "\\textsf{", "\\textrm{", "\\textit{", "\\texttt{", 
	\ "\\textsc{", "\\textsl{", "\\textup{", "\\textnormal", "\\textcolor{",
	\ "\\bfseries", "\\mdseries", "\\bigskip", "\\bibitem",
	\ "\\tiny",  "\\scriptsize", "\\footnotesize", "\\small",
	\ "\\noindent", "\\normalfont", "\normalsize", "\\normalsize", "\\normal", 
	\ "\hfil", "\\hfill", "\\hspace","\\hline", 
	\ "\\large", "\\Large", "\\LARGE", "\\huge", "\\HUGE",
	\ "\\underline{", 
	\ "\\usefont{", "\\fontsize{", "\\selectfont", "\\fontencoding{", "\\fontfamiliy{", "\\fontseries{", "\\fontshape{",
	\ "\\familydefault", 
	\ "\\rmdefault", "\\sfdefault", "\\ttdefault", "\\bfdefault", "\\mddefault", "\\itdefault",
	\ "\\sldefault", "\\scdefault", "\\updefault",  "\\renewcommand{", "\\newcommand{",
	\ "\\input", "\\include{", "\\includeonly{", "\\includegraphics{",  
	\ "\\savebox", "\\sbox", "\\usebox", "\\rule", "\\raisebox{", "\\rotatebox{",
	\ "\\parbox{", "\\mbox{", "\\makebox{", "\\framebox{", "\\fbox{",
	\ "\\medskip", "\\smallskip", "\\vskip", "\\vfil", "\\vfill", "\\vspace{", "\\vbox",
	\ "\\hrule", "\\hrulefill", "\\dotfill", "\\hbox",
	\ "\\thispagestyle{", "\\mathnormal", "\\markright{", "\\markleft{", "\\pagestyle{", "\\pagenumbering{",
	\ "\\addtocounter{",
	\ "\\author{", "\\address{", "\\date{", "\\thanks{", "\\title{",
	\ "\\maketitle",
	\ "\\marginpar", "\\indent", "\\par", "\\sloppy", "\\pagebreak", "\\nopagebreak",
	\ "\\newpage", "\\newline", "\\newtheorem{", "\\linebreak", "\\line", "\\linespread{",
	\ "\\hyphenation{", "\\fussy", "\\eject",
	\ "\\enlagrethispage{", "\\centerline{", "\\centering", "\\clearpage", "\\cleardoublepage",
	\ "\\encodingdefault", 
	\ "\\caption{", "\\chapter", 
	\ "\\opening{", "\\name{", "\\makelabels{", "\\location{", "\\closing{", 
	\ "\\signature{", "\\stopbreaks", "\\startbreaks",
	\ "\\newcounter{", "\\refstepcounter{", 
	\ "\\roman{", "\\Roman{", "\\stepcounter{", "\\setcounter{", 
	\ "\\usecounter{", "\\value{", 
	\ "\\newlength{", "\\setlength{", "\\addtolength{", "\\settodepth{", "\\nointerlineskip", 
	\ "\\addcontentsline{", "\\addtocontents",
	\ "\\settoheight{", "\\settowidth{", "\\stretch{",
	\ "\\seriesdefault", "\\shapedefault",
	\ "\\width", "\\height", "\\depth", "\\todo", "\\totalheight",
	\ "\\footnote{", "\\footnotemark", "\\footnotetetext", 
	\ "\\bibliography{", "\\bibliographystyle{", "\\baselineskip",
	\ "\\flushbottom", "\\onecolumn", "\\raggedbottom", "\\twocolumn",  
	\ "\\alph{", "\\Alph{", "\\arabic{", "\\fnsymbol{", "\\reversemarginpar",
	\ "\\exhyphenpenalty", "\\frontmatter", "\\mainmatter", "\\backmatter",
	\ "\\topmargin", "\\oddsidemargin", "\\evensidemargin", "\\headheight", "\\headsep", 
	\ "\\textwidth", "\\textheight", "\\marginparwidth", "\\marginparsep", "\\marginparpush", "\\footskip", "\\hoffset",
	\ "\\voffset", "\\parindent", "\\paperwidth", "\\paperheight", "\\columnsep", "\\columnseprule", 
	\ "\\theequation", "\\thepage", "\\usetikzlibrary{",
	\ "\\tableofcontents", "\\newfont{", "\\phantom{", "\\DeclareMathOperator",
	\ "\\DeclareRobustCommand", "\\DeclareFixedFont", "\\DeclareMathSymbol", 
	\ "\\DeclareTextFontCommand", "\\DeclareMathVersion", "\\DeclareSymbolFontAlphabet",
	\ "\\DeclareMathDelimiter", "\\DeclareMathAccent", "\\DeclareMathRadical",
	\ "\\SetMathAlphabet", "\\show", "\\CheckCommand", "\\mathnormal",
	\ "\\pounds", "\\magstep{", "\\hyperlink", "\\newenvironment{", 
	\ "\\renewenvironemt{", "\\DeclareFixedFont", "\\layout", "\\parskip",
	\ "\\brokenpenalty", "\\clubpenalty", "\\windowpenalty", "\\hyphenpenalty", "\\tolerance",
	\ "\\frenchspacing", "\\nonfrenchspacing", "\\binoppenalty", "\\exhyphenpenalty", 
	\ "\\displaywindowpenalty", "\\floatingpenalty", "\\interlinepenalty", "\\lastpenalty",
	\ "\\linepenalty", "\\outputpenalty", "\\penalty", "\\postdisplaypenalty", "\\predisplaypenalty", 
	\ "\\repenalty", "\\unpenalty" ]
	
	let g:atp_picture_commands=[ "\\put", "\\circle", "\\dashbox", "\\frame{", 
		    \"\\framebox(", "\\line(", "\\linethickness{",
		    \ "\\makebox(", "\\\multiput(", "\\oval(", "\\put", 
		    \ "\\shortstack", "\\vector(" ]
	" ToDo: end writting layout commands. 
	" ToDo: MAKE COMMANDS FOR PREAMBULE.

	let g:atp_math_commands=["\\begin{", "\\end{", "\\forall", "\\exists", "\\emptyset", "\\aleph", "\\partial",
	\ "\\nabla", "\\Box", "\\bot", "\\top", "\\flat", "\\natural",
	\ "\\mathbf{", "\\mathsf{", "\\mathrm{", "\\mathit{", "\\mathtt{", "\\mathcal{", 
	\ "\\mathop{", "\\mathversion", "\\limits", "\\text{", "\\leqslant", "\\leq", "\\geqslant", "\\geq",
	\ "\\gtrsim", "\\lesssim", "\\gtrless", "\\left", "\\right", 
	\ "\\rightarrow", "\\Rightarrow", "\\leftarrow", "\\Leftarrow", "\\infty", "\\iff", 
	\ "\\oplus", "\\otimes", "\\odot", "\\oint",
	\ "\\leftrightarrow", "\\Leftrightarrow", "\\downarrow", "\\Downarrow", 
	\ "\\overline{", "\\underline{", "\\overbrace{", "\\Uparrow",
	\ "\\Longrightarrow", "\\longrightarrow", "\\Longleftarrow", "\\longleftarrow",
	\ "\\overrightarrow{", "\\overleftarrow{", "\\underrightarrow{", "\\underleftarrow{",
	\ "\\uparrow", "\\nearrow", "\\searrow", "\\swarrow", "\\nwarrow", "\\mapsto", "\\longmapsto",
	\ "\\hookrightarrow", "\\hookleftarrow", "\\gets", "\\to", "\\backslash", 
	\ "\\sum", "\\bigsum", "\\cup", "\\bigcup", "\\cap", "\\bigcap", 
	\ "\\prod", "\\coprod", "\\bigvee", "\\bigwedge", "\\wedge",  
	\ "\\int", "\\bigoplus", "\\bigotimes", "\\bigodot", "\\times",  
	\ "\\smile",
	\ "\\dashv", "\\vdash", "\\vDash", "\\Vert", "\\Vdash", "\\models", "\\sim", "\\simeq", 
	\ "\\prec", "\\preceq", "\\preccurlyeq", "\\precapprox", "\\mid",
	\ "\\succ", "\\succeq", "\\succcurlyeq", "\\succapprox", "\\approx", 
	\ "\\ldots", "\\cdot", "\\cdots", "\\vdots", "\\ddots", "\\circ", 
	\ "\\thickapprox", "\\cong", "\\bullet",
	\ "\\lhd", "\\unlhd", "\\rhd", "\\unrhd", "\\dagger", "\\ddager", "\\dag", "\\ddag", 
	\ "\\varinjlim", "\\varprojlim",
	\ "\\vartriangleright", "\\vartriangleleft", 
	\ "\\triangle", "\\triangledown", "\\trianglerighteq", "\\trianglelefteq",
	\ "\\copyright", "\\textregistered", "\\pounds",
	\ "\\big", "\\Big", "\\Bigg", "\\huge", 
	\ "\\bigr", "\\Bigr", "\\biggr", "\\Biggr",
	\ "\\bigl", "\\Bigl", "\\biggl", "\\Biggl", 
	\ "\\hat", "\\grave", "\\bar", "\\acute", "\\mathring", "\\check", 
	\ "\\dots", "\\dot", "\\vec", "\\breve",
	\ "\\tilde", "\\widetilde" , "\\widehat", "\\ddot", 
	\ "\\sqrt{", "\\frac{", "\\binom{", "\\cline", "\\vline", "\\hline", "\\multicolumn{", 
	\ "\\nouppercase", "\\sqsubseteq", "\\sqsubset", "\\sqsupseteq", "\\sqsupset", 
	\ "\\square", "\\blacksquare",  
	\ "\\nexists", "\\varnothing", "\\Bbbk", "\\circledS", 
	\ "\\complement", "\\hslash", "\\hbar", 
	\ "\\eth", "\\rightrightarrows", "\\leftleftarrows", "\\rightleftarrows", "\\leftrighrarrows", 
	\ "\\downdownarrows", "\\upuparrows", "\\rightarrowtail", "\\leftarrowtail", 
	\ "\\rightharpoondown", "\\rightharpoonup", "\\rightleftharpoons", "\\leftharpoondown", "\\leftharpoonup",
	\ "\\twoheadrightarrow", "\\twoheadleftarrow", "\\rceil", "\\lceil", "\\rfloor", "\\lfloor", 
	\ "\\bigtriangledown", "\\bigtriangleup", "\\ominus", "\\bigcirc", "\\amalg", "\\asymp",
	\ "\\vert", "\\Arrowvert", "\\arrowvert", "\\bracevert", "\\lmoustache", "\\rmoustache",
	\ "\\setminus", "\\sqcup", "\\sqcap", "\\bowtie", "\\owns", "\\oslash",
	\ "\\lnot", "\\notin", "\\neq", "\\smile", "\\frown", "\\equiv", "\\perp",
	\ "\\quad", "\\qquad", "\\stackrel", "\\displaystyle", "\\textstyle", "\\scriptstyle", "\\scriptscriptstyle",
	\ "\\langle", "\\rangle", "\\Diamond", "\\lgroup", "\\rgroup", "\\propto", "\\Join", "\\div", 
	\ "\\land", "\\star", "\\uplus", "\\leadsto", "\\rbrack", "\\lbrack", "\\mho", 
	\ "\\diamondsuit", "\\heartsuit", "\\clubsuit", "\\spadesuit", "\\top", "\\ell", 
	\ "\\imath", "\\jmath", "\\wp", "\\Im", "\\Re", "\\prime", "\\ll", "\\gg", "\\Nabla" ]

	let g:atp_math_commands_PRE=[ "\\diagdown", "\\diagup", "\\subset", "\\subseteq", "\\supset", "\\supsetneq",
		    \ "\\sharp", "\\underline{", "\\underbrace{",  ]

	let g:atp_greek_letters = ['\alpha', '\beta', '\chi', '\delta', '\epsilon', '\phi', '\gamma', '\eta', '\iota', '\kappa', '\lambda', '\mu', '\nu', '\theta', '\pi', '\rho', '\sigma', '\tau', '\upsilon', '\vartheta', '\xi', '\psi', '\zeta', '\Delta', '\Phi', '\Gamma', '\Lambda', '\Mu', '\Theta', '\Pi', '\Sigma', '\Tau', '\Upsilon', '\Omega', '\Psi']

	if !exists("g:atp_local_completion")
	    " if has("python") then fire LocalCommands on startup (BufEnter) if not
	    " when needed.
	    let g:atp_local_completion = ( has("python") ? 2 : 1 )
	endif


	let g:atp_math_commands_non_expert_mode=[ "\\leqq", "\\geqq", "\\succeqq", "\\preceqq", 
		    \ "\\subseteqq", "\\supseteqq", "\\gtrapprox", "\\lessapprox" ]
	 
	" requiers amssymb package:
	let g:atp_ams_negations=[ "\\nless", "\\ngtr", "\\lneq", "\\gneq", "\\nleq", "\\ngeq", "\\nleqslant", "\\ngeqslant", 
		    \ "\\nsim", "\\nconq", "\\nvdash", "\\nvDash", 
		    \ "\\nsubseteq", "\\nsupseteq", 
		    \ "\\varsubsetneq", "\\subsetneq", "\\varsupsetneq", "\\supsetneq", 
		    \ "\\ntriangleright", "\\ntriangleleft", "\\ntrianglerighteq", "\\ntrianglelefteq", 
		    \ "\\nrightarrow", "\\nleftarrow", "\\nRightarrow", "\\nLeftarrow", 
		    \ "\\nleftrightarrow", "\\nLeftrightarrow", "\\nsucc", "\\nprec", "\\npreceq", "\\nsucceq", 
		    \ "\\precneq", "\\succneq", "\\precnapprox", "\\ltimes", "\\rtimes" ]

	let g:atp_ams_negations_non_expert_mode=[ "\\lneqq", "\\ngeqq", "\\nleqq", "\\ngeqq", "\\nsubseteqq", 
		    \ "\\nsupseteqq", "\\subsetneqq", "\\supsetneqq", "\\nsucceqq", "\\precneqq", "\\succneqq" ] 

	" ToDo: add more amsmath commands.
	let g:atp_amsmath_commands=[ "\\boxed", "\\intertext{", "\\multiligngap", "\\shoveleft{", "\\shoveright{", "\\notag", "\\tag", 
		    \ "\\notag", "\\raistag{", "\\displaybreak", "\\allowdisplaybreaks", "\\numberwithin{",
		    \ "\\hdotsfor{" , "\\mspace{",
		    \ "\\negthinspace", "\\negmedspace", "\\negthickspace", "\\thinspace", "\\medspace", "\\thickspace",
		    \ "\\leftroot{", "\\uproot{", "\\overset{", "\\underset{", "\\substack{", "\\sideset{", 
		    \ "\\dfrac", "\\tfrac", "\\cfrac", "\\dbinom{", "\\tbinom{", "\\smash",
		    \ "\\lvert", "\\rvert", "\\lVert", "\\rVert", "\\DeclareMatchOperator{",
		    \ "\\arccos", "\\arcsin", "\\arg", "\\cos", "\\cosh", "\\cot", "\\coth", "\\csc", "\\deg", "\\det",
		    \ "\\dim", "\\exp", "\\gcd", "\\hom", "\\inf", "\\injlim", "\\ker", "\\lg", "\\lim", "\\liminf", "\\limsup",
		    \ "\\log", "\\min", "\\max", "\\Pr", "\\projlim", "\\sec", "\\sin", "\\sinh", "\\sup", "\\tan", "\\tanh",
		    \ "\\varlimsup", "\\varliminf", "\\varinjlim", "\\varprojlim", "\\mod", "\\bmod", "\\pmod", "\\pod", "\\sideset",
		    \ "\\iint", "\\iiint", "\\iiiint", "\\idotsint", "\\tag",
		    \ "\\varGamma", "\\varDelta", "\\varTheta", "\\varLambda", "\\varXi", "\\varPi", "\\varSigma", 
		    \ "\\varUpsilon", "\\varPhi", "\\varPsi", "\\varOmega" ]
	
	" ToDo: integrate in TabCompletion (amsfonts, euscript packages).
	let g:atp_amsfonts=[ "\\mathbb{", "\\mathfrak{", "\\mathscr{" ]

	" not yet supported: in TabCompletion:
	let g:atp_amsextra_commands=[ "\\sphat", "\\sptilde" ]
	let g:atp_fancyhdr_commands=["\\lfoot{", "\\rfoot{", "\\rhead{", "\\lhead{", 
		    \ "\\cfoot{", "\\chead{", "\\fancyhead{", "\\fancyfoot{",
		    \ "\\fancypagestyle{", "\\fancyhf{}", "\\headrulewidth", "\\footrulewidth",
		    \ "\\rightmark", "\\leftmark", "\\markboth{", 
		    \ "\\chaptermark", "\\sectionmark", "\\subsectionmark",
		    \ "\\fancyheadoffset", "\\fancyfootoffset", "\\fancyhfoffset"]


	" ToDo: remove tikzpicture from above and integrate the
	" tikz_envirnoments variable
	" \begin{pgfonlayer}{background} (complete the second argument as
	" well}
	"
	" Tikz command cuold be accitve only in tikzpicture and after \tikz
	" command! There is a way to do that.
	" 
	let g:atp_tikz_environments=['tikzpicture', 'scope', 'pgfonlayer', 'background' ]
	" ToDo: this should be completed as packages.
	let g:atp_tikz_libraries=sort(['arrows', 'automata', 'backgrounds', 'calc', 'calendar', 'chains', 'decorations', 
		    \ 'decorations.footprints', 'decorations.fractals', 
		    \ 'decorations.markings', 'decorations.pathmorphing', 
		    \ 'decorations.replacing', 'decorations.shapes', 
		    \ 'decorations.text', 'er', 'fadings', 'fit',
		    \ 'folding', 'matrix', 'mindmap', 'scopes', 
		    \ 'patterns', 'pteri', 'plothandlers', 'plotmarks', 
		    \ 'plcaments', 'pgflibrarypatterns', 'pgflibraryshapes',
		    \ 'pgflibraryplotmarks', 'positioning', 'replacements', 
		    \ 'shadows', 'shapes.arrows', 'shapes.callout', 'shapes.geometric', 
		    \ 'shapes.gates.logic.IEC', 'shapes.gates.logic.US', 'shapes.misc', 
		    \ 'shapes.multipart', 'shapes.symbols', 'topaths', 'through', 'trees' ])
	" tikz keywords = begin without '\'!
	" ToDo: add more keywords: done until page 145.
	" ToDo: put them in a correct order!!!
	" ToDo: completion for arguments in brackets [] for tikz commands.
	let g:atp_tikz_commands=[ "\\begin", "\\end", "\\matrix", "\\node", "\\shadedraw", 
		    \ "\\draw", "\\tikz", "\\tikzset",
		    \ "\\path", "\\filldraw", "\\fill", "\\clip", "\\drawclip", "\\foreach", "\\angle", "\\coordinate",
		    \ "\\useasboundingbox", "\\tikztostart", "\\tikztotarget", "\\tikztonodes", "\\tikzlastnode",
		    \ "\\pgfextra", "\\endpgfextra", "\\verb", "\\coordinate", 
		    \ "\\pattern", "\\shade", "\\shadedraw", "\\colorlet", "\\definecolor",
		    \ "\\pgfmatrixnextcell" ]
	let g:atp_tikz_keywords=[ 'draw', 'node', 'matrix', 'anchor=', 'top', 'bottom',  
		    \ 'west', 'east', 'north', 'south', 'at', 'thin', 'thick', 'semithick', 'rounded', 'corners',
		    \ 'controls', 'and', 'circle', 'step', 'grid', 'very', 'style', 'line', 'help',
		    \ 'color', 'arc', 'curve', 'scale', 'parabola', 'line', 'ellipse', 'bend', 'sin', 'rectangle', 'ultra', 
		    \ 'right', 'left', 'intersection', 'xshift=', 'yshift=', 'shift', 'near', 'start', 'above', 'below', 
		    \ 'end', 'sloped', 'coordinate', 'cap', 'shape=', 'label=', 'every', 
		    \ 'edge', 'point=', 'loop', 'join', 'distance', 'sharp', 'rotate=', 'blue', 'red', 'green', 'yellow', 
		    \ 'black', 'white', 'gray', 'name',
		    \ 'text', 'width=', 'inner', 'sep=', 'baseline', 'current', 'bounding', 'box', 
		    \ 'canvas', 'polar', 'radius', 'barycentric', 'angle=', 'opacity', 
		    \ 'solid', 'phase', 'loosly', 'dashed', 'dotted' , 'densly', 
		    \ 'latex', 'diamond', 'double', 'smooth', 'cycle', 'coordinates', 'distance',
		    \ 'even', 'odd', 'rule', 'pattern', 
		    \ 'stars', 'shading', 'ball', 'axis', 'middle', 'outer', 'transorm', 'fill',
		    \ 'fading', 'horizontal', 'vertical', 'light', 'dark', 'button', 'postaction', 'out',
		    \ 'circular', 'shadow', 'scope', 'borders', 'spreading', 'false', 'position', 'midway',
		    \ 'paint', 'from', 'to', 'solution=', 'global', 'delta' ]
	let g:atp_tikz_library_arrows_keywords	= [ 'reversed', 'stealth', 'triangle', 'open', 
		    \ 'hooks', 'round', 'fast', 'cap', 'butt'] 
	let g:atp_tikz_library_automata_keywords=[ 'state', 'accepting', 'initial', 'swap', 
		    \ 'loop', 'nodepart', 'lower', 'upper', 'output']  
	let g:atp_tikz_library_backgrounds_keywords=[ 'background', 'show', 'inner', 'frame', 'framed',
		    \ 'tight', 'loose', 'xsep', 'ysep']

	let g:atp_tikz_library_calendar_commands=[ '\calendar', '\tikzmonthtext' ]
	let g:atp_tikz_library_calendar_keywords=[ 'week list', 'dates', 'day', 'day list', 'month', 'year', 'execute', 
		    \ 'before', 'after', 'downward', 'upward' ]
	let g:atp_tikz_library_chain_commands=[ '\chainin' ]
	let g:atp_tikz_library_chain_keywords=[ 'chain', 'start chain', 'on chain', 'continue chain', 
		    \ 'start branch', 'branch', 'going', 'numbers', 'greek' ]
	let g:atp_tikz_library_decorations_commands=[ '\\arrowreversed' ]
	let g:atp_tikz_library_decorations_keywords=[ 'decorate', 'decoration', 'lineto', 'straight', 'zigzag',
		    \ 'saw', 'random steps', 'bent', 'aspect', 'bumps', 'coil', 'curveto', 'snake', 
		    \ 'border', 'brace', 'segment lenght', 'waves', 'ticks', 'expanding', 
		    \ 'crosses', 'triangles', 'dart', 'shape', 'width=', 'size', 'sep', 'shape backgrounds', 
		    \ 'between', 'along', 'path', 
		    \ 'Koch curve type 1', 'Koch curve type 1', 'Koch snowflake', 'Cantor set', 'footprints',
		    \ 'foot',  'stride lenght', 'foot', 'foot', 'foot of', 'gnome', 'human', 
		    \ 'bird', 'felis silvestris', 'evenly', 'spread', 'scaled', 'star', 'height=', 'text',
		    \ 'mark', 'reset', 'marks' ]
	let g:atp_tikz_library_er_keywords	= [ 'entity', 'relationship', 'attribute', 'key']
	let g:atp_tikz_library_fadings_keywords	= [ 'with', 'fuzzy', 'percent', 'ring' ]
	let g:atp_tikz_library_fit_keywords	= [ 'fit']
	let g:atp_tikz_library_matrix_keywords	= ['matrix', 'of', 'nodes', 'math', 'matrix of math nodes', 
		    \ 'matrix of nodes', 'delimiter', 
		    \ 'rmoustache', 'column sep=', 'row sep=' ] 
	let g:atp_tikz_library_mindmap_keywords	= [ 'mindmap', 'concept', 'large', 'huge', 'extra', 'root', 'level',
		    \ 'connection', 'bar', 'switch', 'annotation' ]
	let g:atp_tikz_library_folding_commands	= ["\\tikzfoldingdodecahedron"]
	let g:atp_tikz_library_folding_keywords	= ['face', 'cut', 'fold'] 
        let g:atp_tikz_library_patterns_keywords	= ['lines', 'fivepointed', 'sixpointed', 'bricks', 'checkerboard',
		    \ 'crosshatch', 'dots']
	let g:atp_tikz_library_petri_commands	= ["\\tokennumber" ]
        let g:atp_tikz_library_petri_keywords	= ['place', 'transition', 'pre', 'post', 'token', 'child', 'children', 
		    \ 'are', 'tokens', 'colored', 'structured' ]
	let g:atp_tikz_library_pgfplothandlers_commands	= ["\\pgfplothandlercurveto", "\\pgfsetplottension",
		    \ "\\pgfplothandlerclosedcurve", "\\pgfplothandlerxcomb", "\\pgfplothandlerycomb",
		    \ "\\pgfplothandlerpolarcomb", "\\pgfplothandlermark{", "\\pgfsetplotmarkpeat{", 
		    \ "\\pgfsetplotmarkphase", "\\pgfplothandlermarklisted{", "\\pgfuseplotmark", 
		    \ "\\pgfsetplotmarksize{", "\\pgfplotmarksize" ]
        let g:atp_tikz_library_plotmarks_keywords	= [ 'asterisk', 'star', 'oplus', 'oplus*', 'otimes', 'otimes*', 
		    \ 'square', 'square*', 'triangle', 'triangle*', 'diamond*', 'pentagon', 'pentagon*']
	let g:atp_tikz_library_shadow_keywords 	= ['general shadow', 'shadow', 'drop shadow', 'copy shadow', 'glow' ]
	let g:atp_tikz_library_shapes_keywords 	= ['shape', 'center', 'base', 'mid', 'trapezium', 'semicircle', 'chord', 'regular polygon', 'corner', 'star', 'isoscales triangle', 'border', 'stretches', 'kite', 'vertex', 'side', 'dart', 'tip', 'tail', 'circular', 'sector', 'cylinder', 'minimum', 'height=', 'width=', 'aspect', 'uses', 'custom', 'body', 'forbidden sign', 'cloud', 'puffs', 'ignores', 'starburst', 'random', 'signal', 'pointer', 'tape', 
		    \ 'single', 'arrow', 'head', 'extend', 'indent', 'after', 'before', 'arrow box', 'shaft', 
		    \ 'lower', 'upper', 'split', 'empty', 'part', 
		    \ 'callout', 'relative', 'absolute', 'shorten',
		    \ 'logic gate', 'gate', 'inputs', 'inverted', 'radius', 'use', 'US style', 'CDH style', 'nand', 'and', 'or', 'nor', 'xor', 'xnor', 'not', 'buffer', 'IEC symbol', 'symbol', 'align', 
		    \ 'cross out', 'strike out', 'length', 'chamfered rectangle' ]
	let g:atp_tikz_library_topath_keywords	= ['line to', 'curve to', 'out', 'in', 'relative', 'bend', 'looseness', 'min', 'max', 'control', 'loop']
	let g:atp_tikz_library_through_keywords	= ['through']
	let g:atp_tikz_library_trees_keywords	= ['grow', 'via', 'three', 'points', 'two', 'child', 'children', 'sibling', 'clockwise', 'counterclockwise', 'edge', 'parent', 'fork'] 

	let g:atp_TodoNotes_commands = [ '\todo{', '\listoftodos', '\missingfigure' ] 
	let g:atp_TodoNotes_todo_options = 
		    \ [ 'disable', 'color=', 'backgroundcolor=', 'linecolor=', 'bordercolor=', 
		    \ 'line', 'noline', 'inline', 'noinline', 'size=', 'list', 'nolist', 
		    \ 'caption=', 'prepend', 'noprepend', 'fancyline' ]   
	"Todo: PackageOptions are not yet done.  
	let g:atp_TodoNotes_packageOptions = [ 'textwidth', 'textsize', 
			    \ 'prependcaption', 'shadow', 'dvistyle', 'figwidth', 'obeyDraft' ]

	let g:atp_TodoNotes_missingfigure_options = [ 'figwidth=' ]
if !exists("g:atp_MathOpened")
    let g:atp_MathOpened = 1
endif
" augroup ATP_MathOpened
"     au!
"     au Syntax tex :let g:atp_MathOpened = 1
" augroup END

let g:atp_math_modes=[ ['\%([^\\]\|^\)\%(\\\|\\\{3}\)(','\%([^\\]\|^\)\%(\\\|\\\{3}\)\zs)'],
	    \ ['\%([^\\]\|^\)\%(\\\|\\\{3}\)\[','\%([^\\]\|^\)\%(\\\|\\\{3}\)\zs\]'],	
	    \ ['\\begin{align', '\\end{alig\zsn'], 	['\\begin{gather', '\\end{gathe\zsr'], 
	    \ ['\\begin{falign', '\\end{flagi\zsn'], 	['\\begin[multline', '\\end{multlin\zse'],
	    \ ['\\begin{equation', '\\end{equatio\zsn'],
	    \ ['\\begin{\%(display\)\?math', '\\end{\%(display\)\?mat\zsh'] ] 

" Completion variables for \pagestyle{} and \thispagestyle{} LaTeX commands.
let g:atp_pagestyles = [ 'plain', 'headings', 'empty', 'myheadings' ]
let g:atp_fancyhdr_pagestyles = [ 'fancy' ]

" Completion variable for \pagenumbering{} LaTeX command.
let g:atp_pagenumbering = [ 'arabic', 'roman', 'Roman', 'alph', 'Alph' ]

" SIunits
let g:atp_siuinits= [
 \ '\addprefix', '\addunit', '\ampere', '\amperemetresecond', '\amperepermetre', '\amperepermetrenp',
 \ '\amperepersquaremetre', '\amperepersquaremetrenp', '\angstrom', '\arad', '\arcminute', '\arcsecond',
 \ '\are', '\atomicmass', '\atto', '\attod', '\barn', '\bbar',
 \ '\becquerel', '\becquerelbase', '\bel', '\candela', '\candelapersquaremetre', '\candelapersquaremetrenp',
 \ '\celsius', '\Celsius', '\celsiusbase', '\centi', '\centid', '\coulomb',
 \ '\coulombbase', '\coulombpercubicmetre', '\coulombpercubicmetrenp', '\coulombperkilogram', '\coulombperkilogramnp', '\coulombpermol',
 \ '\coulombpermolnp', '\coulombpersquaremetre', '\coulombpersquaremetrenp', '\cubed', '\cubic', '\cubicmetre',
 \ '\cubicmetreperkilogram', '\cubicmetrepersecond', '\curie', '\dday', '\deca', '\decad',
 \ '\deci', '\decid', '\degree', '\degreecelsius', '\deka', '\dekad',
 \ '\derbecquerel', '\dercelsius', '\dercoulomb', '\derfarad', '\dergray', '\derhenry',
 \ '\derhertz', '\derjoule', '\derkatal', '\derlumen', '\derlux', '\dernewton',
 \ '\derohm', '\derpascal', '\derradian', '\dersiemens', '\dersievert', '\dersteradian',
 \ '\dertesla', '\dervolt', '\derwatt', '\derweber', '\electronvolt', '\exa',
 \ '\exad', '\farad', '\faradbase', '\faradpermetre', '\faradpermetrenp', '\femto',
 \ '\femtod', '\fourth', '\gal', '\giga', '\gigad', '\gram',
 \ '\graybase', '\graypersecond', '\graypersecondnp', '\hectare', '\hecto', '\hectod',
 \ '\henry', '\henrybase', '\henrypermetre', '\henrypermetrenp', '\hertz', '\hertzbase',
 \ '\hour', '\joule', '\joulebase', '\joulepercubicmetre', '\joulepercubicmetrenp', '\jouleperkelvin',
 \ '\jouleperkelvinnp', '\jouleperkilogram', '\jouleperkilogramkelvin', '\jouleperkilogramkelvinnp', '\jouleperkilogramnp', '\joulepermole',
 \ '\joulepermolekelvin', '\joulepermolekelvinnp', '\joulepermolenp', '\joulepersquaremetre', '\joulepersquaremetrenp', '\joulepertesla',
 \ '\jouleperteslanp', '\katal', '\katalbase', '\katalpercubicmetre', '\katalpercubicmetrenp', '\kelvin',
 \ '\kilo', '\kilod', '\kilogram', '\kilogrammetrepersecond', '\kilogrammetrepersecondnp', '\kilogrammetrepersquaresecond', '\kilogrammetrepersquaresecondnp', '\kilogrampercubicmetre', '\kilogrampercubicmetrecoulomb', '\kilogrampercubicmetrecoulombnp', '\kilogrampercubicmetrenp',
 \ '\kilogramperkilomole', '\kilogramperkilomolenp', '\kilogrampermetre', '\kilogrampermetrenp', '\kilogrampersecond', '\kilogrampersecondcubicmetre',
 \ '\kilogrampersecondcubicmetrenp', '\kilogrampersecondnp', '\kilogrampersquaremetre', '\kilogrampersquaremetrenp', '\kilogrampersquaremetresecond', '\kilogrampersquaremetresecondnp',
 \ '\kilogramsquaremetre', '\kilogramsquaremetrenp', '\kilogramsquaremetrepersecond', '\kilogramsquaremetrepersecondnp', '\kilowatthour', '\liter',
 \ '\litre', '\lumen', '\lumenbase', '\lux', '\luxbase', '\mega',
 \ '\megad', '\meter', '\metre', '\metrepersecond', '\metrepersecondnp', '\metrepersquaresecond',
 \ '\metrepersquaresecondnp', '\micro', '\microd', '\milli', '\millid', '\minute',
 \ '\mole', '\molepercubicmetre', '\molepercubicmetrenp', '\nano', '\nanod', '\neper',
 \ '\newton', '\newtonbase', '\newtonmetre', '\newtonpercubicmetre', '\newtonpercubicmetrenp', '\newtonperkilogram', '\newtonperkilogramnp', '\newtonpermetre', '\newtonpermetrenp', '\newtonpersquaremetre', '\newtonpersquaremetrenp', '\NoAMS', '\no@qsk', '\ohm', '\ohmbase', '\ohmmetre',
 \ '\one', '\paminute', '\pascal', '\pascalbase', '\pascalsecond', '\pasecond',
 \ '\per', '\period@active', '\persquaremetresecond', '\persquaremetresecondnp', '\peta', '\petad',
 \ '\pico', '\picod', '\power', '\@qsk', '\quantityskip', '\rad',
 \  '\radian', '\radianbase', '\radianpersecond', '\radianpersecondnp', '\radianpersquaresecond', '\radianpersquaresecondnp', '\reciprocal', '\rem', '\roentgen', '\rp', '\rpcubed',
 \ '\rpcubic', '\rpcubicmetreperkilogram', '\rpcubicmetrepersecond', '\rperminute', '\rpersecond', '\rpfourth',
 \ '\rpsquare', '\rpsquared', '\rpsquaremetreperkilogram', '\second', '\siemens', '\siemensbase',
 \ '\sievert', '\sievertbase', '\square', '\squared', '\squaremetre', '\squaremetrepercubicmetre',
 \ '\squaremetrepercubicmetrenp', '\squaremetrepercubicsecond', '\squaremetrepercubicsecondnp', '\squaremetreperkilogram', '\squaremetrepernewtonsecond', '\squaremetrepernewtonsecondnp',
 \ '\squaremetrepersecond', '\squaremetrepersecondnp', '\squaremetrepersquaresecond', '\squaremetrepersquaresecondnp', '\steradian', '\steradianbase',
 \ '\tera', '\terad', '\tesla', '\teslabase', '\ton', '\tonne',
 \ '\unit', '\unitskip', '\usk', '\volt', '\voltbase', '\voltpermetre',
 \ '\voltpermetrenp', '\watt', '\wattbase', '\wattpercubicmetre', '\wattpercubicmetrenp', '\wattperkilogram',
 \ '\wattperkilogramnp', '\wattpermetrekelvin', '\wattpermetrekelvinnp', '\wattpersquaremetre', '\wattpersquaremetrenp', '\wattpersquaremetresteradian',
 \ '\wattpersquaremetresteradiannp', '\weber', '\weberbase', '\yocto', '\yoctod', '\yotta',
 \ '\yottad', '\zepto', '\zeptod', '\zetta', '\zettad' ]
 " }}}

" Scan packge file:
let g:atp_package_dict={}
function! g:atp_package_dict.ScanPackage(package_name,...) dict "{{{1
    " Todo: add { if the command takes an argument {} but only if it doesn't have
    " arguments [].
    " Fails to find options in geometry.sty since there options are defined using:
    " \define@key{Gm}{option_name}... macro defined in keyval.sty.

if get(self, a:package_name, {}) == {} 
    let self[a:package_name]={}
endif
" a:1 = [ 'options', 'commands' ] (list of things to scan if
" a:1 = [ 'options!' ] then make scan even if the value exists.
let modes = ( !a:0 ? [ 'options', 'commands' ] : a:1 )
" a:2 == 1 : recursive search (\RequirePackage, \input)
let recursive = ( a:0 < 2 ? 0 : a:1 )
let modes_dict = {'options' : 0, 'commands' : 0}
for mode in modes
    let m = matchstr(mode, '\w*\ze!\?')
    let modes_dict[m]= get(self[a:package_name], m, ['@']) == ['@'] || ( mode != m )
endfor
if modes_dict['options'] == 0 && modes_dict['commands'] == 0
    return self
endif
if !has("python")
    return {'options' : []}
endif
python << EOF
import vim, re, subprocess, os.path
package = vim.eval("a:package_name")


# Pattern to find declared options:
option_pat = re.compile('\\\\(?:KOMA@|X)?Declare(?:Void|Local|(?:Bi)?Bool(?:ean)?|String|Standard|Switch|Type|Unicode|Entry|Bibliography|Caption|Complementary|Quote)?Option(?:Beamer)?X?\*?(?:<\w+>)?\s*(?:%\s*\n\s)?{((?:\w|\d|-|_|\*)+)}|\\\\Declare(?:Exclusive|Local|Void)?Options\*?\s*{((?:\n|[^}])+)}')
# This adds \define@key{}{}[]{} command (keyval) but this might be used not only for package options:
# option_pat = re.compile('\\\\(?:KOMA@|X)?Declare(?:Void|Local|(?:Bi)?Bool(?:ean)?|String|Standard|Switch|Type|Unicode|Entry|Bibliography|Caption|Complementary|Quote)?Option(?:Beamer)?X?\*?(?:<\w+>)?\s*(?:%\s*\n\s)?{((?:\w|\d|-|_|\*)+)}|\\\\Declare(?:Exclusive|Local|Void)?Options\*?\s*{((?:\n|[^}])+)}|\\\\define@key\s*{[^}]*}\s*{\s*([^}]*)\s*}')

# for example geometry.sty uses the followin commands to set options:
# \def\Gm@setkeys{\setkeys{Gm}}%	THIS SETS THE Gm SET OF KEYS
# \def\Gm@processconfig{%
#   \let\Gm@origExecuteOptions\ExecuteOptions
#   \let\ExecuteOptions\Gm@setkeys%	AND HERE IT IS EXECUTED
#   \InputIfFileExists{geometry.cfg}{}{}
#   \let\ExecuteOptions\Gm@origExecuteOptions}%

# This pattern is not working with:
# \KOMA@DeclareStandardOption%
#   {oneside}{twoside=false}
# /usr/local/texlive/2011/texmf-dist/tex/latex/koma-script/scrbook.cls

# Pattern to find command name without the leading '\':
command_pat = re.compile('(?:^\s*\\\\e\?def|\\\\(?:newcommand|Declare(?:Document|Uni|(?:Multi)?Cite|Page|Url|Robust|Text(?:Font|Composite)?|OldFont|)Command(?:Default)?\*?))\s*(?:{\\\\([^}]*)|\\\\([^#\[{]*))', re.MULTILINE)
# only accept \def and \edef statements at the begining of a line. This excludes internal variables (inside groups: {...}).

# How to work with this :
# /usr/local/texlive/2011/texmf-dist/tex/latex/biblatex/biblatex.sty
#\DeclareRangeCommands{%
#  \ \,\space\nobreakspace\addspace\addnbspace
#  \addthinspace\addnbthinspace\addlowpenspace
#  \addhighpenspace\addlpthinspace\addhpthinspace
#  \adddotspace\addabbrvspace\&\psq\psqq
#  \bibrangedash\bibdatedash\textendash\textemdash}
#\DeclarePageCommands{\pno\ppno}
#
# Another problem in babel.def:
# \ifx\@undefined\DeclareTextFontCommand
#    \DeclareRobustCommand{\textlatin}[1]{\leavevmode{\latintext #1}}
# puts \DeclareRobustCommand to defined commands.
#
# /usr/local/texlive/2011/texmf-dist/tex/latex/index/index.sty
# it is \RequirePackage by /usr/local/texlive/2011/texmf-dist/tex/latex/index/bibref.sty
# it uses \def to define commands.

def remove_duplicates(seq, idfun=None):
    # found at http://www.peterbe.com/plog/uniqifiers-benchmark
    # order preserving
    if idfun is None:
	def idfun(x): return x
    seen = {}
    result = []
    for item in seq:
	marker = idfun(item)
	if marker in seen: continue
	seen[marker] = 1
	result.append(item)
    return result

def Kpsewhich(package):
    kpsewhich = subprocess.Popen(['kpsewhich', package], stdout=subprocess.PIPE)
    kpsewhich.wait()
    if kpsewhich.returncode == 0:
        return os.path.abspath(re.match('(.*)\n', kpsewhich.stdout.read()).group(1))
    else:
        return ''


def ScanPackage(package, o=True, c=True):

    options = []
    commands = []

    package_file = Kpsewhich(package)
    # check the variable: @classoptionslist
    if package_file != '':
        vim.command("let path='"+str(package_file)+"'")
        package_fo = open(package_file, 'r')
        package_f  = package_fo.read()
        # vim.command("let self['file']="+decode(package_fo))
        package_fo.close()
        # print(package_file)
        if o:
            # We can cut the package_f variable at \ProcessOptions:
            o_match = re.match('((?:.|\n)*)\\\\ProcessOptions', package_f)
            # how to do that more efficiently (find the regexp and cut at its byte position)?
            if o_match:
                o_f = o_match.group(1)
            else:
                o_f = package_f
            matches = re.findall(option_pat, o_f)
            for match in matches:
                option_list = re.sub('\n|\s|%', '', ",".join(match)).split(",")
                option_list = [item for item in option_list if re.match('(?:\w|\d|-|_|\*)+$',item)]
                options+=option_list
        if c:
            vim.command("echomsg '[ATP]: processing commands from "+package+"'")
            matches = re.findall(command_pat, package_f)
            for match in matches:
                for m in match:
                    if not re.search('@', m) and not re.search('\\\\', m) and \
			not re.match('Declare\w*(?:Command|Option)', m) and m != '':
                        commands.append(re.match('(\S*)', m).group(1))
    return [options, remove_duplicates(commands)]

require_package_pat = re.compile('\\\\RequirePackage\s*{([^}]*)}')
def RequiredPackage(package):
    #scan package for input files
    package_file = Kpsewhich(package)
    package_fo = open(package_file, 'r!')
    package_f = package_fo.read()
    package_fo.close()
    matches = re.findall(require_package_pat, package_f)
    input_files = []
    for match in matches:
        m=match
        [ base, ext ] = os.path.splitext(m)
        if ext == '':
            m += '.sty'
        input_files.append(m)
    return input_files

# List of all commands: 
re_commands=[]
# dictionary { package_name : commands }:
recursive_dict = {}
# do not scan files twice:
did_files=[]
def RecursiveSearch(package):
    # recursive search for options and commands

    global re_commands
    global recursive_dict
    global did_files
    i_files = RequiredPackage(Kpsewhich(package))
    did_files.append(package)
    # print(input_files)
    re_commands_add = ScanPackage(package, o=False, c=True)[1]
    recursive_dict[package]=remove_duplicates(re_commands_add)
    # print("re_commands_add="+str(re_commands_add))
    for c in re_commands_add:
	if not c in re_commands:
            re_commands.append(c)
    for p in i_files:
	if not p in did_files:
            # print("rs: "+p)
            RecursiveSearch(p)


if vim.eval("recursive") == '0':
    o = ( str(vim.eval("modes_dict['options']")) == '1' )
    c = ( str(vim.eval("modes_dict['commands']")) == '1' )
    [options, commands]=ScanPackage(package, o, c)
else:
    RecursiveSearch(package)
    vim.command("let recursive_dict="+str(recursive_dict))
    commands = re_commands
    # print("re_commands="+str(re_commands))
    o = ( str(vim.eval("modes_dict['options']")) == '1' )
    if o:
        options=ScanPackage(package, o, c=False)[0]
    else:
        options=[]


vim.command("let options = "+str(options))
vim.command("let commands= "+str(commands))
EOF
if exists('path')
    let self[a:package_name]['path'] = path
endif
if exists('options') && modes_dict['options']
    let self[a:package_name]['options']=options
endif
if exists('commands') && modes_dict['commands']
    let self[a:package_name]['commands']=map(commands, "'\\'.v:val")
endif
if exists('recursive_dict')
    call map(recursive_dict, 'map(v:val, "''\\''.v:val")')
    for key in keys(recursive_dict)
	if get(self, key, {}) == {}
	    let self[key]={}
	endif
	let self[key]['commands']=recursive_dict[key]
    endfor
endif
return self
endfunction "}}}1
" vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1
ftplugin/ATP_files/dictionaries/SIunits	[[[1
289
addprefix
addunit
ampere
amperemetresecond
amperepermetre
amperepermetrenp
amperepersquaremetre
amperepersquaremetrenp
angstrom
arad
arcminute
arcsecond
are
atomicmass
atto
attod
barn
bbar
becquerel
becquerelbase
bel
candela
candelapersquaremetre
candelapersquaremetrenp
celsius
Celsius
celsiusbase
centi
centid
coulomb
coulombbase
coulombpercubicmetre
coulombpercubicmetrenp
coulombperkilogram
coulombperkilogramnp
coulombpermol
coulombpermolnp
coulombpersquaremetre
coulombpersquaremetrenp
cubed
cubic
cubicmetre
cubicmetreperkilogram
cubicmetrepersecond
curie
dday
deca
decad
deci
decid
degree
degreecelsius
deka
dekad
derbecquerel
dercelsius
dercoulomb
derfarad
dergray
derhenry
derhertz
derjoule
derkatal
derlumen
derlux
dernewton
derohm
derpascal
derradian
dersiemens
dersievert
dersteradian
dertesla
dervolt
derwatt
derweber
electronvolt
exa
exad
farad
faradbase
faradpermetre
faradpermetrenp
femto
femtod
fourth
gal
giga
gigad
gram
graybase
graypersecond
graypersecondnp
hectare
hecto
hectod
henry
henrybase
henrypermetre
henrypermetrenp
hertz
hertzbase
hour
joule
joulebase
joulepercubicmetre
joulepercubicmetrenp
jouleperkelvin
jouleperkelvinnp
jouleperkilogram
jouleperkilogramkelvin
jouleperkilogramkelvinnp
jouleperkilogramnp
joulepermole
joulepermolekelvin
joulepermolekelvinnp
joulepermolenp
joulepersquaremetre
joulepersquaremetrenp
joulepertesla
jouleperteslanp
katal
katalbase
katalpercubicmetre
katalpercubicmetrenp
kelvin
kilo
kilod
kilogram
kilogrammetrepersecond
kilogrammetrepersecondnp
kilogrammetrepersquaresecond
kilogrammetrepersquaresecondnp
kilogrampercubicmetre
kilogrampercubicmetrecoulomb
kilogrampercubicmetrecoulombnp
kilogrampercubicmetrenp
kilogramperkilomole
kilogramperkilomolenp
kilogrampermetre
kilogrampermetrenp
kilogrampersecond
kilogrampersecondcubicmetre
kilogrampersecondcubicmetrenp
kilogrampersecondnp
kilogrampersquaremetre
kilogrampersquaremetrenp
kilogrampersquaremetresecond
kilogrampersquaremetresecondnp
kilogramsquaremetre
kilogramsquaremetrenp
kilogramsquaremetrepersecond
kilogramsquaremetrepersecondnp
kilowatthour
liter
litre
lumen
lumenbase
lux
luxbase
mega
megad
meter
metre
metrepersecond
metrepersecondnp
metrepersquaresecond
metrepersquaresecondnp
micro
microd
milli
millid
minute
mole
molepercubicmetre
molepercubicmetrenp
nano
nanod
neper
newton
newtonbase
newtonmetre
newtonpercubicmetre
newtonpercubicmetrenp
newtonperkilogram
newtonperkilogramnp
newtonpermetre
newtonpermetrenp
newtonpersquaremetre
newtonpersquaremetrenp
NoAMS
no@qsk
ohm
ohmbase
ohmmetre
one
paminute
pascal
pascalbase
pascalsecond
pasecond
per
period@active
persquaremetresecond
persquaremetresecondnp
peta
petad
pico
picod
power
@qsk
quantityskip
rad
radian
radianbase
radianpersecond
radianpersecondnp
radianpersquaresecond
radianpersquaresecondnp
reciprocal
rem
roentgen
rp
rpcubed
rpcubic
rpcubicmetreperkilogram
rpcubicmetrepersecond
rperminute
rpersecond
rpfourth
rpsquare
rpsquared
rpsquaremetreperkilogram
second
siemens
siemensbase
sievert
sievertbase
square
squared
squaremetre
squaremetrepercubicmetre
squaremetrepercubicmetrenp
squaremetrepercubicsecond
squaremetrepercubicsecondnp
squaremetreperkilogram
squaremetrepernewtonsecond
squaremetrepernewtonsecondnp
squaremetrepersecond
squaremetrepersecondnp
squaremetrepersquaresecond
squaremetrepersquaresecondnp
steradian
steradianbase
tera
terad
tesla
teslabase
ton
tonne
unit
unitskip
usk
volt
voltbase
voltpermetre
voltpermetrenp
watt
wattbase
wattpercubicmetre
wattpercubicmetrenp
wattperkilogram
wattperkilogramnp
wattpermetrekelvin
wattpermetrekelvinnp
wattpersquaremetre
wattpersquaremetrenp
wattpersquaremetresteradian
wattpersquaremetresteradiannp
weber
weberbase
yocto
yoctod
yotta
yottad
zepto
zeptod
zetta
zettad
ftplugin/ATP_files/dictionaries/ams_dictionary	[[[1
161
Bmatrix
DeclareMatchOperator
Pr
align
alignat
allowdisplaybreaks
arccos
arcsin
arg
bmatrix
bmod
boxed
cfrac
cos
cosh
cot
coth
csc
dbinom
deg
det
dfrac
dim
displaybreak
equation
exp
flalign
gather
gcd
gneq
hdotsfor
hom
idotsint
iiiint
iiint
iint
inf
injlim
intertext
ker
lVert
leftroot
lg
lim
liminf
limsup
lneq
lneqq
log
ltimes
lvert
mathbb
mathfrak
mathscr
max
medspace
min
mod
mspace
multiligngap
multline
nLeftarrow
nLeftrightarrow
nRightarrow
nconq
negmedspace
negthickspace
negthinspace
ngeq
ngeqq
ngeqq
ngeqslant
ngtr
nleftarrow
nleftrightarrow
nleq
nleqq
nleqslant
nless
notag
notag
nprec
npreceq
nrightarrow
nsim
nsubseteq
nsubseteqq
nsucc
nsucceq
nsucceqq
nsupseteq
nsupseteqq
ntriangleleft
ntrianglelefteq
ntriangleright
ntrianglerighteq
numberwithin
nvDash
nvdash
overset
pmatrix
pmod
pod
precnapprox
precneq
precneqq
projlim
rVert
raistag
rtimes
rvert
sec
shoveleft
shoveright
sideset
sideset
sin
sinh
smallmatrix
smash
sphat
split
sptilde
subeqations
subsetneq
subsetneqq
substack
substack
succneq
succneqq
sup
supsetneq
supsetneqq
tag
tag
tan
tanh
tbinom
tfrac
thickspace
thinspace
underset
uproot
varDelta
varGamma
varLambda
varOmega
varPhi
varPi
varPsi
varSigma
varTheta
varUpsilon
varXi
varinjlim
varliminf
varlimsup
varprojlim
varsubsetneq
varsupsetneq
vmatrix
ftplugin/ATP_files/dictionaries/dictionary	[[[1
937
Alph
Arrowvert
Bbbk
Big
Bigg
Biggl
Biggm
Biggr
Bigl
Bigm
Bigr
Box
COLON
CheckCommand
DeclareFixedFont
DeclareFixedFont
DeclareMathAccent
DeclareMathDelimiter
DeclareMathOperator
DeclareMathRadical
DeclareMathSymbol
DeclareMathVersion
DeclareRobustCommand
DeclareSymbolFontAlphabet
DeclareTextFontCommand
Diamond
Downarrow
HUGE
Huge
Im
Join
LARGE
LaTeX
LaTeXe
Large
Leftarrow
Leftrightarrow
Longleftarrow
Longrightarrow
NeedsTeXFormat
PLSlash
PLdateending
Re
Rightarrow
Roman
SS
SetMathAlphabet
TeX
Uparrow
Vdash
a4paper
a5paper
abbrv
abovedisplayshortskip
abovedisplayskip
abstract
abstract
abstractname
acute
addcontentsline
address
addtime
addtocontents
addtocounter
addtolength
addvspace
aleph
align
align*
alph
amalg
amsmath
amsthm
and
appendix
appendixname
approx
arabic
array
arraycolsep
arrayrulewidth
arraystretch
arrowvert
article
asymp
author
b5paper
backmatter
backslash
bar
bar
baselineskip
baselinestretch
batchmode
begin
belowdisplayshortskip
belowdisplayskip
bezier
bf
bfdefault
bfseries
bibindent
bibitem
bibliography
bibliographystyle
bibname
big
bigcap
bigcirc
bigcup
bigg
biggl
biggm
biggr
Biggr
bigl
Bigl
bigm
Bigm
bigodot
bigoplus
bigotimes
bigr
Bigr
bigskip
bigskipamount
bigsum
bigtriangledown
bigtriangleup
bigvee
bigwedge
binom
blacksquare
blg
bmatrix
Bmatrix
boldmath
boldsymbol
book
booklet
bot
botfigrule
bottmofraction
bottomnumber
bowtie
boxedminipage
bp
bracevert
breve
bullet
calc
calc
cap
capt-of
caption
caption2
capt-of
cases
cc
ccaption
ccname
cdot
cdots
cdotscenter
centering
cercle
cfrac
changebar
chapter
chapterbib
chaptername
check
circ
circledS
cite
cleardoublepage
clearpage
cline
clock
closing
clubsuit
cm
COLON
columnsep
columnseprule
columnwidth
complement
conference
cong
contentsline
contentsname
coprod
copyright
cup
dag
dagger
dashbox
dashv
date
dbinom
dblfigure
dblfloatpage
dblfloatsep
dbltextfloatsep
dbltopfraction
dbltopnumber
dcolumn
dd
ddag
ddager
ddot
ddots
depth
description
dfrac
diagdown
diagup
diamondsuit
displaylimits
displaymath
displaystyle
div
document
documentclass
dot
dotfill
dots
doublerulesep
downarrow
downbracefill
downdownarrows
draft
dropping
dywiz
eject
ell
em
emph
empty
emptyset
encl
enclname
end
endfloat
enlagrethispage
enlargethispage
enskip
enspace
ensuremath
enumerate
enumi
enumii
enumiii
enumiv
eqnarray
eqref
equation
equation*
equiv
errorstopmode
eth
eucal
eufrak
evensidemargin
everyship
ex
executivepaper
exhyphenpenalty
exists
expdlist
extracolsep
extramark
fancybox
fancyhdr
fbox
fboxrule
fboxsep
figure
figurename
file
filecontents
final
flafter
flat
fleqn
floatflt
floatpagefraction
floatsep
flushbottom
flushleft
flushright
fn2end
fnpara
fnsymbol
fontenc
fontencoding
fontfamiliy
fontseries
fontshape
fontsize
footheight
footmisc
footnote
footnotemark
footnoterule
footnotesep
footnotesize
footnotetetext
footnotetext
footnpag
footskip
forall
frac
frame
framebox
frenchspacing
frontmatter
frown
frown
ftnright
fussy
gather
genfrac
geometry
geq
geqslant
gets
gg
glossary
glossaryentry
graphicx
graphpaper
grave
gtrless
gtrsim
hat
hbar
hbox
headheight
headheihgt
headings
headsep
heartsuit
height
helvet
hfill
hhline
hline
hoffset
hookleftarrow
hookrightarrow
hrulefill
hslash
hspace
huge
hyperlink
hyperref
hyphenation
iff
ifthen
imath
in
include
includegraphics
includeonly
indent
indentfirst
index
indexentry
indexname
indexspace
infty
input
inputenc
int
intertext
intextsep
invisible
it
itdefault
item
itemindent
itemize
itemsep
itshape
jmath
jot
kill
label
labelenumi
labelenumii
labelenumiii
labelenumiv
labelitemi
labelitemii
labelitemiii
labelitemiv
labelsep
labelwidth
land
landscape
langle
large
latexsym
layout
lbrack
lceil
ldots
leadsto
left
leftarrow
leftarrowfill
leftarrowtail
lefteqn
leftharpoondown
leftharpoonup
leftleftarrows
leftmargin
leftmargini
leftmarginii
leftmarginiii
leftmarginiv
leftmarginv
leftmarginvi
leftmark
leftrighrarrows
leftrightarrow
legalpaper
leq
leqno
leqslant
lesssim
letter
letterpaper
letterspace
lfloor
lgroup
lhd
lhead
limits
line
linebreak
linespread
linethickness
linewidth
list
listfigurename
listfiles
listoffigures
listoftables
listparindent
ll
lmoustache
lnot
location
longleftarrow
longmapsto
longrightarrow
longtable
lq
lrbox
lscape
magstep
mainmatter
makeatletter
makeatother
makebox
makeglossary
makeidx
makeindex
makelabel
makelabels
maketitle
manyfoot
mapsto
marginpar
marginparpush
marginparsep
marginparwidth
markboth
markleft
markright
math
mathbb
mathbf
mathbin
mathcal
mathclose
mathfrak
mathindent
mathit
mathnormal
mathop
mathopen
mathord
mathpunct
mathrel
mathring
mathrm
mathscr
mathsf
mathstrut
mathtt
mathversion
mbox
mddefault
mdseries
medmuskip
medskip
medskipamount
mho
mid
minipage
minitoc
minus
mkern
mm
models
moreverbatim
mpfootnote
mu
multicol
multicolumn
multilanguage
multiput
multirow
myheadings
nabla
name
natural
nearrow
neq
newcommand
newcounter
newenvironment
newfont
newlength
newline
newpage
newsavebox
newtheorem
nexists
nocite
nofiles
noindent
nointerlineskip
nolimits
nolinebreak
nomathsymbols
nonfrenchspacing
nonumber
nopagebreak
normal
normalfont
normalsize
not
notag
note
notin
notitlepage
nouppercase
nu
num
numberline
numline
numprint
nwarrow
oddsidemargin
odot
oint
oldstyle
ominus
onecolumn
oneside
onlynotes
onlyslides
openany
openbib
opening
openright
operatorname
oplus
oslash
otimes
oval
overbrace
overlay
overleftarrow
overline
overrightarrow
owns
page
pagebreak
pagenumbering
pageref
pagestyle
paperheight
paperwidth
par
paragraph
parbox
parbox
parindent
parsep
parskip
part
partial
partname
partopsep
pauza
pc
perp
phantom
phi
pi
picture
plain
plmath
plus
pmb
pmod
polski
polski
poptabs
pounds
ppauza
prec
precapprox
preccurlyeq
preceq
prefixing
prime
printindex
prod
propto
protect
providecommand
ps
pt
puonds
pushtabs
put
qbezier
qbeziermax
qquad
quad
quotation
quote
ragged2e
raggedbottom
raggedleft
raggedright
raisebox
rangle
ratio
rbrack
rceil
real
ref
refname
refstepcounter
relsize
renewcommand
renewenvironemt
renewenvironment
report
reversemarginpar
rfloor
rgroup
rhd
rhead
right
rightarrow
rightarrowfill
rightarrowtail
rightharpoondown
rightharpoonup
rightleftarrows
rightleftharpoons
rightmargin
rightmark
rightrightarrows
rm
rmdefault
rmfamily
rmoustache
roman
rotate
rotating
rq
rule
samepage
savebox
sb
sbox
sc
scdefault
scriptscriptstyle
scriptsize
scriptstyle
scrollmode
scshape
searrow
secnumdepth
section
sectionmark
see
seename
selectfont
selectlanguage
setcounter
setlength
setminus
settime
settodepth
settoheight
settowidth
sf
sfdefault
sffamily
shadethm
shadow
shapepar
sharp
shortstack
show
showlabels
sidecap
signature
sim
simeq
sin
sl
sldefault
slide
slides
sloppy
sloppybar
slshape
small
smallskip
smallskipamount
smile
smile
soul
sp
space
spadesuit
sqcap
sqcup
sqrt
sqsubset
sqsubseteq
sqsupset
sqsupseteq
square
ss
stackrel
star
startbreaks
stepcounter
stop
stopbreaks
stretch
strut
subfigure
subfigure
subitem
subparagraph
subsection
subset
subseteq
subsubitem
subsubsection
succ
succapprox
succcurlyeq
succeq
sum
supressfloats
supset
supsetneq
swarrow
symbol
symbol
tabbing
tabcolsep
table
tablename
tableofcontents
tabular
tabularx
tag
tan
tbinom
telephone
text
textbf
textbullet
textcircled
textcolor
textcompwordmark
textemdash
textendash
textexclamdown
textfloatsep
textfraction
textheight
textit
textmd
textnormal
textperiodcenter
textquestiondown
textquotedblleft
textquotedblright
textquoteleft
textquoteright
textregistered
textrm
textsc
textsf
textsl
textstyle
textsuperscript
texttt
textup
textvisiblespace
textwidth
tfrac
thanks
the
thebibliography
theequation
theindex
theorem
thepage
thesection
theta
thickapprox
thicklines
thickmuskip
thinlines
thispagestyle
threeparttable
tilde
time
times
tiny
title
titlepage
to
tocdepth
today
top
top
topfigrule
topfraction
topmargin
topmargin
topmargin
topsep
topskip
topskip
totalheight
totalnumber
triangle
triangledown
trianglelefteq
trianglerighteq
trivlist
tt
ttdefault
ttfamily
twocolumn
twocolumn
twoheadleftarrow
twoheadrightarrow
twoside
typein
typein
typeout
typeout
ulem
ulem
unboldmath
underbrace
underleftarrow
underline
underrightarrow
unlhd
unrhd
unsort
unsrt
uparrow
upbracefill
updefault
uplus
upshape
upshape
upuparrows
usebox
usebox
usecounter
usefont
usepackage
usetikzlibrary
vDash
value
varnothing
vartriangleleft
vartriangleright
vbox
vdash
vdots
vec
vector
verb
verb
verbatim
verse
vert
vfil
vfill
visible
vline
vmargin
voffset
vskip
vspace
wedge
widehat
widetilde
width
wp
wrapfig
xleftarrow
xrightarrow
ftplugin/ATP_files/dictionaries/greek	[[[1
38
alpha
beta
chi
delta 
epsilon
varepsilon
phi
psi
gamma
eta
kappa
lambda
mu
nu
pi
theta
rho
sigma
tau
upsilon
varsigma
vartheta
omega
xi
zeta
Delta
Psi
Phi
Gamma
Lambda
Mu
Nu
Pi
Theta
Sigma
Tau
Upsilon
Omega
ftplugin/ATP_files/dictionaries/tikz	[[[1
346
CDH style
Cantor set
IEC symbol
Koch curve type 1
Koch snowflake
US style
above
absolute
after
align
along
anchor
and
angle
annotation
arc
are
arrow box
arrow
aspect
asterisk
at
attribute
axis
ball
bar
barycentric
base
baseline
before
below
bend
bent
between
bird
black
blue
body
border
borders
bottom
bounding
box
brace
branch
bricks
buffer
bumps
butt
button
callout
canvas
cap
center
chain
chamfered rectangle
checkerboard
child
children
chord
circle
circular
clockwise
cloud
coil
color
colored
column sep=
concept
connection
continue chain
control
controls
coordinate
coordinates
copy shadow
corner
corners
counterclockwise
cross out
crosses
crosshatch
current
curve to
curve
curveto
custom
cut
cycle
cylinder
dark
dart
dashed
dates
day list
day
decorate
decoration
delimiter
densly
diamond
diamond*
distance
dots
dotted
double
downward
draw
drop shadow
east
edge
ellipse
empty
end
entity
even
evenly
every
execute
expanding
extend
extra
face
fading
false
fast
felis silvestris
fit
fivepointed
fold
foot of
foot
footprints
forbidden sign
fork
from
fuzzy
gate
general shadow
glow
gnome
going
gray
greek
green
grid
grow
head
height
help
hooks
horizontal
huge
human
ignores
in
indent
inner
inputs
intersection
inverted
isoscales triangle
join
key
kite
label
large
latex
left
length
level
light
line to
line
lines
lineto
logic gate
loop
looseness
loosly
lower
mark
marks
math
matrix of math nodes
matrix of nodes
matrix
max
mid
middle
midway
min
mindmap
minimum
month
nand
near
node
nodes
nor
north
not
numbers
odd
of
on chain
opacity
open
oplus
oplus*
or
otimes
otimes*
out
outer
paint
parabola
parent
part
path
pattern
pentagon
pentagon*
percent
phase
place
point
pointer
points
polar
position
post
postaction
pre
puffs
radius
random steps
random
rectangle
red
regular polygon
relationship
relative
reset
reversed
right
ring
rmoustache
root
rotate
round
rounded
row sep=
rule
saw
scale
scaled
scope
sector
segment lenght
semicircle
semithick
sep
shading
shadow
shaft
shape backgrounds
shape
sharp
shift
shorten
sibling
side
signal
sin
single
sixpointed
size
sloped
smooth
snake
solid
south
split
spread
spreading
square
square*
star
starburst
stars
start branch
start chain
start
stealth
step
straight
stretches
stride lenght
strike out
structured
style
switch
symbol
tail
tape
text
thick
thin
three
through
ticks
tip
to
token
tokens
top
transition
transorm
trapezium
triangle
triangle*
triangles
two
ultra
upper
upward
use
uses
vertex
vertical
very
via
waves
week list
west
white
width
with
xnor
xor
xshift
year
yellow
yshift
zigzag
ftplugin/ATP_files/evince_sync.py	[[[1
241
#!/usr/bin/python
# -*- coding: utf-8 -*-

# This file was part of the Gedit Synctex plugin.
# Slightly modified by _vicious_ ...
#
# Copyright (C) 2010 Jose Aliste <jose.aliste@gmail.com>
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free Software
# Foundation; either version 2 of the Licence, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public Licence for more
# details.
#
# You should have received a copy of the GNU General Public Licence along with
# this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
# Street, Fifth Floor, Boston, MA  02110-1301, USA

import dbus, subprocess, time
from optparse import OptionParser
parser  = OptionParser()
parser.add_option("-e", "--evince_version", default=None, type="int", action="store", dest="EVINCE_VERSION")
(options, args) = parser.parse_args()
EVINCE_VERSION=options.EVINCE_VERSION
if EVINCE_VERSION is None:
    import subprocess, re
    cmd = ["evince", "--version"]
    ev_ver=subprocess.Popen(cmd, stdout=subprocess.PIPE)
    ev_ver.wait()
    ev_version = ev_ver.stdout.read()
    EVINCE_VERSION = int(re.search('(\d)(?:\d|\.)+\s*$', ev_version).group(1))

RUNNING, CLOSED = range(2)

EV_DAEMON_PATH = "/org/gnome/evince/Daemon"
EV_DAEMON_NAME = "org.gnome.evince.Daemon"
EV_DAEMON_IFACE = "org.gnome.evince.Daemon"

EVINCE_PATH = "/org/gnome/evince/Evince"
EVINCE_IFACE = "org.gnome.evince.Application"

EV_WINDOW_IFACE = "org.gnome.evince.Window"




class EvinceWindowProxy:
    """A DBUS proxy for an Evince Window."""
    daemon = None
    bus = None

    def __init__(self, uri, spawn = False, logger = None):
        self._log = logger
        self.uri = uri
        self.spawn = spawn
        self.status = CLOSED
        self.source_handler = None
        self.dbus_name = ''
        self._handler = None
        try:
            if EvinceWindowProxy.bus is None:
                EvinceWindowProxy.bus = dbus.SessionBus()

            if EvinceWindowProxy.daemon is None:
                EvinceWindowProxy.daemon = EvinceWindowProxy.bus.get_object(EV_DAEMON_NAME,
                                                EV_DAEMON_PATH,
                                                follow_name_owner_changes=True)
            self._get_dbus_name(False)

        except dbus.DBusException:
            if self._log:
                self._log.debug("Could not connect to the Evince Daemon")

    def _get_dbus_name(self, spawn):
        EvinceWindowProxy.daemon.FindDocument(self.uri,spawn,
                     reply_handler=self.handle_find_document_reply,
                     error_handler=self.handle_find_document_error,
                     dbus_interface = EV_DAEMON_IFACE)

    def handle_find_document_error(self, error):
        if self._log:
            self._log.debug("FindDocument DBus call has failed")

    def handle_find_document_reply(self, evince_name):
        if self._handler is not None:
            handler = self._handler
        else:
            handler = self.handle_get_window_list_reply
        if evince_name != '':
            self.dbus_name = evince_name
            self.status = RUNNING
            self.evince = EvinceWindowProxy.bus.get_object(self.dbus_name, EVINCE_PATH)
            self.evince.GetWindowList(dbus_interface = EVINCE_IFACE,
                          reply_handler = handler,
                          error_handler = self.handle_get_window_list_error)

    def handle_get_window_list_error (self, e):
        if self._log:
            self._log.debug("GetWindowList DBus call has failed")

    def handle_get_window_list_reply (self, window_list):
        if len(window_list) > 0:
            window_obj = EvinceWindowProxy.bus.get_object(self.dbus_name, window_list[0])
            self.window = dbus.Interface(window_obj,EV_WINDOW_IFACE)
            self.window.connect_to_signal("Closed", self.on_window_close)
            self.window.connect_to_signal("SyncSource", self.on_sync_source)
        else:
            #That should never happen. 
            if self._log:
                self._log.debug("GetWindowList returned empty list")


    def set_source_handler (self, source_handler):
        self.source_handler = source_handler

    def on_window_close(self):
        self.window = None
        self.status = CLOSED

    def on_sync_source(self, input_file, source_link, timestamp):
        if self.source_handler is not None:
            if EVINCE_VERSION >= 3:
                self.source_handler(input_file, source_link, timestamp)
            else:
                self.source_handler(input_file, source_link)

    def SyncView(self, input_file, data, timestamp):
        if self.status == CLOSED:
            if self.spawn:
                self._tmp_syncview = [input_file, data, timestamp];
                self._handler = self._syncview_handler
                self._get_dbus_name(True)
        else:
            self.window.SyncView(input_file, data, timestamp, dbus_interface = "org.gnome.evince.Window")

    def _syncview_handler(self, window_list):
        self.handle_get_window_list_reply(window_list)

        if self.status == CLOSED:
            return False
        if EVINCE_VERSION >= 3:
            self.window.SyncView(self._tmp_syncview[0],
                                 self._tmp_syncview[1],
                                 self._tmp_syncview[2],
                                 dbus_interface="org.gnome.evince.Window")
        else:
            self.window.SyncView(self._tmp_syncview[0],
                                 self._tmp_syncview[1],
                                 dbus_interface="org.gnome.evince.Window")
        del self._tmp_syncview
        self._handler = None
        return True

## This file can be used as a script to support forward search and backward search in vim.
## It should be easy to adapt to other editors. 
##  evince_dbus  pdf_file  line_source input_file
if __name__ == '__main__':
    import dbus.mainloop.glib, gobject, glib, sys, os

    def print_usage():
        print('The usage (to make evince sync ... will exit when sync done) is evince_vim_dbus EVINCE output_file line_number input_file from the directory of output_file.')
        print('The usage (to make gvim sync in response to evince clicks, keeps running till killed) is evince_vim_dbus GVIM gvim_server_name output_file input_file from the directory of output_file.')
        sys.exit(1)

    if len(sys.argv)!=5:
        print_usage()

    if sys.argv[1] == 'EVINCE':
        try:
            line_number = int(sys.argv[3])
        except ValueError:
            print_usage()

        output_file = sys.argv[2]
        input_file  = sys.argv[4]
        if output_file[0] != '/':
            path_output = os.getcwd() + '/' + output_file
        else:
            path_output = output_file
        if input_file[0] == '/':
            path_input   = os.path.dirname(input_file) + '/./' + os.path.basename(input_file)
        else:
            path_input   = os.getcwd() + '/./' + os.path.basename(input_file)

        if not os.path.isfile(path_output):
            print("OUTPUT PATH "+path_output)
            print_usage()

        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        a = EvinceWindowProxy('file://' + path_output, True )

        def sync_view(ev_window, path_input, line_number):
            if EVINCE_VERSION >= 3:
                ev_window.SyncView (path_input, (line_number, 1), 0)
            else:
                ev_window.SyncView (path_input, (line_number, 1))
            exit(0)

        glib.timeout_add(400, sync_view, a, path_input, line_number)
        loop = gobject.MainLoop()
        loop.run()

    elif sys.argv[1] == 'GVIM' or sys.argv[1] == 'VIM':
        if sys.argv[1] == 'GVIM':
            progname = 'gvim'
        else:
            progname = 'vim'
        gvim_server_name = sys.argv[2]
        output_file = sys.argv[3]
        input_file  = sys.argv[4]
        if output_file[0] == '/':
            path_output = output_file
        else:
            path_output  = os.getcwd() + '/' + output_file
        if input_file[0] == '/':
            path_input   = input_file
        else:
            path_input   = os.getcwd() + '/' + input_file

        if not os.path.isfile(path_input):
            print_usage()

        def source_view_handler(input_file, source_link, timestamp):
            print(progname+' --servername "' + gvim_server_name + '" --remote +' + str(source_link[0]) + ' ' + input_file)
            os.system(progname+' --servername "' + gvim_server_name + '" --remote +' + str(source_link[0]) + ' ' + input_file)

        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        a = EvinceWindowProxy('file://' + path_output, True )

        a.set_source_handler(source_view_handler)
        loop = gobject.MainLoop()
        loop.run()
    else:
        print_usage()


# ex:ts=4:et:
ftplugin/ATP_files/latex_log.py	[[[1
500
#!/usr/bin/python
# -*- coding: utf-8 -*-

# Usage: latex_log.py {tex_log_file}
# Produces a "._log" file.

# Author: Marcin Szamotulski
# http://atp-vim.sourceforge.net
#
# Copyright Statement: 
#     This file is a part of Automatic Tex Plugin for Vim.
#
#     Automatic Tex Plugin for Vim is free software: you can redistribute it
#     and/or modify it under the terms of the GNU General Public License as
#     published by the Free Software Foundation, either version 3 of the
#     License, or (at your option) any later version.
# 
#     Automatic Tex Plugin for Vim is distributed in the hope that it will be
#     useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#     General Public License for more details.
# 
#     You should have received a copy of the GNU General Public License along
#     with Automatic Tex Plugin for Vim.  If not, see <http://www.gnu.org/licenses/>.

# INFO: 
# This is a python script which reads latex log file (which path is gven as
# the only argument) and it writes back a log messages which are in the
# following format:
# WARNING_TYPE::FILE::INPUT_LINE::INPUT_COL::MESSAGE (ADDITIONAL_INFO)
# this was intendent to be used for vim quick fix:
# set errorformat=LaTeX\ %tarning::%f::%l::%c::%m,Citation\ %tarning::%f::%l::%c::%m,Reference\ %tarning::%f::%l::%c::%m,Package\ %tarning::%f::%l::%c::%m,hbox\ %tarning::%f::%l::%c::%m,LaTeX\ %tnfo::%f::%l::%c::%m,LaTeX\ %trror::%f::%l::%c::%m
#
# The fowllowing WARNING_TYPEs are available:
# LaTeX Warning
# Citation Warning
# Reference Warning
# Package Warning
# hbox Warning                  : Overfull and Underfull hbox warnings
# LaTeX Font Warning
# LaTeX Font Info
# LaTeX Info
# LaTeX Error
# Input File
# Input Package                 : includes packges and document class

# Note: when FILE,INPUT_LINE,INPUT_COL doesn't exists 0 is put.

# It will work well when the tex file was compiled with a big value of 
# max_print_line (for example with `max_print_line=2000 latex file.tex')
# so that latex messages are not broken into lines.

# The scripts assumes the default encoding to be utf-8. Though you will not see
# errors since decode(errors='replace') is used, that is bytes not recognized
# will be substituted with '?'.

import sys, re, os, os.path, fnmatch

def shift_dict( dictionary, nr ):
    ''' Add nr to every value of dictionary.

    '''
    for key in dictionary.iterkeys():
        dictionary[key]+=nr
    return dictionary

if sys.platform.startswith('linux'):
    log_to_path = "/tmp/latex_log.log"
else:
    log_to_path = None

def rewrite_log(input_fname, output_fname=None, check_path=False, project_dir="", project_tmpdir=""):
    # this function rewrites LaTeX log file (input_fname) to output_fname,
    # changeing its format to something readable by Vim.
    # check_path -- ATP process files in a temporary directory, with this
    # option the files under project_tmpdir will be written using project_dir
    # (this is for the aux file).

    if output_fname is None:
        output_fname = os.path.splitext(input_fname)[0]+"._log"

    try:
        if sys.version_info < (3, 0):
            log_file = open(input_fname, 'r')
        else:
            # We are assuming the default encoding (utf-8)
            log_file = open(input_fname, 'r', errors='replace')
    except IOError:
        print("IOError: cannot open %s file for reading" % input_fname)
        sys.exit(1)
    else:
        log_stream = log_file.read()
    finally:
        log_file.close()
    # Todo: In python3 there is UnicodeDecodeError. I should remove all the
    # bytes where python cannot decode the character.

    dir = os.path.dirname(os.path.abspath(input_fname))
    os.chdir(dir)

    # Filter the log_stream: remove all unbalanced brackets (:)
    # some times the log file contains unbalanced brackets!
    # This removes all the lines after 'Overfull \hbox' message until first non
    # empty line and all lines just after 'Runaway argument?'.
    log_lines = log_stream.split("\n")
    output_lines = []
    idx = 0
    remove = False
    prev_line = ""
    overfull = False
    runawayarg = False
    for line in log_lines:
        idx+=1
        match_overfull   = re.match('(Over|Under)full \\\\hbox ',line)
        match_runawayarg = re.match('Runaway argument\?',prev_line)
        if match_overfull or match_runawayarg:
            if match_overfull:
                overfull = True
            if match_runawayarg:
                runawayarg = True
            remove = True
        elif re.match('^\s*$', line) and overfull:
            remove = False
            overfull = False
        elif runawayarg:
            remove = False
            runawayarg = False
        if not remove or match_overfull:
            output_lines.append(line)
        prev_line = line
    log_stream='\n'.join(output_lines)
    del output_lines
    output_data = []
    log_lines = log_stream.split("\n")
    global log_to_path
    if log_to_path:
        try:
            log_fo=open(log_to_path, 'w')
        except IOError:
            print("IOError: cannot open %s file for writting" % log_to_path)
        else:
            log_fo.write(log_stream)
        finally:
            log_fo.close()

    # File stack
    file_stack = []

    line_nr = 1
    col_nr = 1

    # Message Patterns:
    latex_warning_pat = re.compile('(LaTeX Warning: )')
    latex_warning= "LaTeX Warning"

    font_warning_pat = re.compile('LaTeX Font Warning: ')
    font_warning = "LaTeX Font Warning"

    font_info_pat = re.compile('LaTeX Font Info: ')
    font_info = "LaTeX Font Info"

    package_warning_pat = re.compile('Package (\w+) Warning: ')
    package_warning = "Package Warning"

    package_info_pat = re.compile('Package (\w+) Info: ')
    package_info = "Package Info"

    hbox_info_pat = re.compile('(Over|Under)full \\\\hbox ')
    hbox_info = "hbox Warning"

    latex_info_pat = re.compile('LaTeX Info: ')
    latex_info = "LaTeX Info"

    latex_emergency_stop_pat = re.compile('\! Emergency stop\.')
    latex_emergency_stop = "LaTeX Error"

    latex_error_pat = re.compile('\! (?:LaTeX Error: |Package (\w+) Error: )?')
    latex_error = "LaTeX Error"

    input_package_pat = re.compile('(?:Package: |Document Class: )')
    input_package = 'Input Package'

    open_dict = {}
    # This dictionary is of the form:
    # { file_name : number_of_brackets_opened_after_the_file_name_was_found ... }

    idx=-1
    line_up_to_col = ""
    # This variable stores the current line up to the current column.
    for char in log_stream:
        idx+=1
        if char == "\n":
            line_nr+=1
            col_nr=0
            line_up_to_col = ""
        else:
            col_nr+=1
            line_up_to_col += char
        if char == "(" and not re.match('l\.\d+', line_up_to_col):
            # If we are at the '(' bracket, check for the file name just after it.
            line = log_lines[line_nr-1][col_nr:]
            fname_re = re.match('([^\(\)]*\.(?:tex|sty|cls|cfg|def|aux|fd|out|bbl|blg|bcf|lof|toc|lot|ind|idx|thm|synctex\.gz|pdfsync|clo|lbx|mkii|run\.xml|spl|snm|nav|brf|mpx|ilg|maf|glo|mtc[0-9]+))', line)
            if fname_re:
                fname = os.path.abspath(fname_re.group(1))
                if check_path and fnmatch.fnmatch(fname, project_tmpdir+"*"):
                    # ATP specific path rewritting:
                    fname = os.path.normpath(os.path.join(project_dir, os.path.relpath(fname, project_tmpdir)))
                output_data.append(["Input File", fname, "0", "0", "Input File"])
                file_stack.append(fname)
                open_dict[fname]=0
            open_dict = shift_dict(open_dict, 1)
        elif char == ")" and not re.match('l\.\d+', line_up_to_col):
            if len(file_stack) and not( re.match('\!', log_lines[line_nr-1]) or re.match('\s{5,}',log_lines[line_nr-1]) or re.match('l\.\d+', log_lines[line_nr-1])):
            # If the ')' is in line that we check, then substrackt 1 from values of
            # open_dict and pop both the open_dict and the file_stack. 
                open_dict = shift_dict(open_dict, -1)
                if open_dict[file_stack[-1]] == 0:
                    open_dict.pop(file_stack[-1])
                    file_stack.pop()

        line = log_lines[line_nr-1][col_nr:]
        if col_nr == 0:
            # Check for the error message in the current line 
            # (that's why we only check it when col_nr == 0)
            try:
                last_file = file_stack[-1]
            except IndexError:
                last_file = "0"
            if check_path and fnmatch.fnmatch(last_file, project_tmpdir+"*"):
                # ATP specific path rewritting:
                last_file = os.path.normpath(os.path.join(project_dir, os.path.relpath(last_file, project_tmpdir)))
            if re.match(latex_warning_pat, line):
                # Log Message: 'LaTeX Warning: '
                input_line = re.search('on input line (\d+)', line)
                warning_type = re.match('LaTeX Warning: (Citation|Reference)', line)
                if warning_type:
                    wtype = warning_type.group(1)
                else:
                    wtype = ""
                msg = re.sub('\s+on input line (\d+)', '', re.sub(latex_warning_pat,'', line))
                if msg == "":
                    msg = " "
                if input_line:
                    output_data.append([wtype+" "+latex_warning, last_file, input_line.group(1), "0", msg])
                else:
                    output_data.append([latex_warning, last_file, "0", "0", msg])
            elif re.match(font_warning_pat, line):
                # Log Message: 'LaTeX Font Warning: '
                input_line = re.search('on input line (\d+)', line)
                if not input_line and line_nr < len(log_lines) and re.match('\(Font\)', log_lines[line_nr]):
                    input_line = re.search('on input line (\d+)', line)
                if not input_line and line_nr+1 < len(log_lines) and re.match('\(Font\)', log_lines[line_nr+1]):
                    input_line = re.search('on input line (\d+)', log_lines[line_nr+1])
                msg = re.sub(' on input line \d+', '', re.sub(font_warning_pat,'', line))
                if msg == "":
                    msg = " "
                i=0
                while line_nr+i < len(log_lines) and re.match('\(Font\)', log_lines[line_nr+i]):
                    msg += re.sub(' on input line \d+', '', re.sub('\(Font\)\s*', ' ', log_lines[line_nr]))
                    i+=1
                if not re.search("\.\s*$", msg):
                    msg = re.sub("\s*$", ".", msg)
                if input_line:
                    output_data.append([font_warning, last_file, input_line.group(1), "0", msg])
                else:
                    output_data.append([font_warning, last_file, "0", "0", msg])
            elif re.match(font_info_pat, line):
                # Log Message: 'LaTeX Font Info: '
                input_line = re.search('on input line (\d+)', line)
                if not input_line and line_nr < len(log_lines) and re.match('\(Font\)', log_lines[line_nr]):
                    input_line = re.search('on input line (\d+)', log_lines[line_nr])
                if not input_line and line_nr+1 < len(log_lines) and re.match('\(Font\)', log_lines[line_nr+1]):
                    input_line = re.search('on input line (\d+)', log_lines[line_nr+1])
                msg = re.sub(' on input line \d+', '', re.sub(font_info_pat,'', line))
                if msg == "":
                    msg = " "
                i=0
                while line_nr+i < len(log_lines) and re.match('\(Font\)', log_lines[line_nr+i]):
                    msg += re.sub(' on input line \d+', '', re.sub('\(Font\)\s*', ' ', log_lines[line_nr]))
                    i+=1
                if not re.search("\.\s*$", msg):
                    msg = re.sub("\s*$", ".", msg)
                if input_line:
                    output_data.append([font_info, last_file, input_line.group(1), "0", msg])
                else:
                    output_data.append([font_info, last_file, "0", "0", msg])
            elif re.match(package_warning_pat, line):
                # Log Message: 'Package (\w+) Warning: '
                package = re.match(package_warning_pat, line).group(1)
                input_line = re.search('on input line (\d+)', line)
                msg = re.sub(package_warning_pat,'', line)
                if line_nr < len(log_lines):
                    nline = log_lines[line_nr]
                    i=0
                    while re.match('\('+package+'\)',nline):
                        msg+=re.sub('\('+package+'\)\s*', ' ', nline)
                        if not input_line:
                            input_line = re.search('on input line (\d+)', nline)
                        i+=1
                        if line_nr+i < len(log_lines):
                            nline = log_lines[line_nr+i]
                        else:
                            break
                if msg == "":
                    msg = " "
                msg = re.sub(' on input line \d+', '', msg)
                if input_line:
                    output_data.append([package_warning, last_file, input_line.group(1), "0", msg+" ("+package+")"])
                else:
                    output_data.append([package_warning, last_file, "0", "0", msg+" ("+package+")"])
            elif re.match(package_info_pat, line):
                # Log Message: 'Package (\w+) Info: '
                package = re.match(package_info_pat, line).group(1)
                input_line = re.search('on input line (\d+)', line)
                msg = re.sub(package_info_pat,'', line)
                if line_nr < len(log_lines):
                    nline = log_lines[line_nr]
                    i=0
                    while re.match('\('+package+'\)',nline):
                        msg+=re.sub('\('+package+'\)\s*', ' ', nline)
                        if not input_line:
                            input_line = re.search('on input line (\d+)', nline)
                        i+=1
                        if line_nr+i < len(log_lines):
                            nline = log_lines[line_nr+i]
                        else:
                            break
                if msg == "":
                    msg = " "
                msg = re.sub(' on input line \d+', '', msg)
                if input_line:
                    output_data.append([package_info, last_file, input_line.group(1), "0", msg+" ("+package+")"])
                else:
                    output_data.append([package_info, last_file, "0", "0", msg+" ("+package+")"])
            elif re.match(hbox_info_pat, line):
                # Log Message: '(Over|Under)full \\\\hbox'
                input_line = re.search('at lines? (\d+)(?:--(?:\d+))?', line)
                if re.match('Underfull', line):
                    h_type = 'Underfull '
                else:
                    h_type = 'Overfull '
                msg = h_type+'\\hbox '+str(re.sub(hbox_info_pat, '', line))
                if msg == "":
                    msg = " "
                if input_line:
                    output_data.append([hbox_info, last_file, input_line.group(1), "0", msg])
                else:
                    output_data.append([hbox_info, last_file, "0", "0", msg])
            elif re.match(latex_info_pat, line):
                # Log Message: 'LaTeX Info: '
                input_line = re.search('on input line (\d+)', line)
                msg = re.sub(' on input line \d+', '', re.sub(latex_info_pat,'', line))
                if msg == "":
                    msg = " "
                if input_line:
                    output_data.append([latex_info, last_file, input_line.group(1), "0", msg])
                else:
                    output_data.append([latex_info, last_file, "0", "0", msg])
            elif re.match(input_package_pat, line):
                # Log Message: 'Package: ', 'Document Class: '
                msg = re.sub(input_package_pat, '', line)
                if msg == "":
                    msg = " "
                output_data.append([input_package, last_file, "0", "0", msg])
            elif re.match(latex_emergency_stop_pat, line):
                # Log Message: '! Emergency stop.'
                msg = "Emergency stop."
                nline = log_lines[line_nr]
                match = re.match('<\*>\s+(.*)', nline)
                if match:
                    e_file = match.group(1)
                else:
                    e_file = "0"
                i=-1
                while True:
                    i+=1
                    try:
                        nline = log_lines[line_nr-1+i]
                        line_m = re.match('\*\*\*\s+(.*)', nline)
                        if line_m:
                            rest = line_m.group(1)
                            break
                        elif i>50:
                            rest = ""
                            break
                    except IndexError:
                        rest = ""
                        break
                msg += " "+rest
                output_data.append([latex_emergency_stop, e_file, "0", "0",msg])
            elif re.match(latex_error_pat, line):
                # Log Message: '\! (?:LaTeX Error: |Package (\w+) Error: )?'
                # get the line unmber of the error
                match = re.search('on input line (\d+)', line)
                input_line = (match and [match.group(1)] or [None])[0]
                i=-1
                while True:
                    i+=1
                    try:
                        nline = log_lines[line_nr-1+i]
                        line_m = re.match('l\.(\d+) (.*)', nline)
                        if line_m:
                            if input_line is None:
                                input_line = line_m.group(1)
                            rest = line_m.group(2)+re.sub('^\s*', ' ', log_lines[line_nr+i])
                            break
                        elif i>50:
                            if input_line is None:
                                input_line="0"
                            rest = ""
                            break
                    except IndexError:
                        if input_line is None:
                            input_line="0"
                        rest = ""
                        break
                msg = re.sub(latex_error_pat, '', line)
                if msg == "":
                    msg = " "
                p_match = re.match('! Package (\w+) Error', line)
                if p_match:
                    info = match.group(1)
                elif rest:
                    info = rest
                else:
                    info = ""
                if re.match('\s*\\\\]\s*', info) or re.match('\s*$', info):
                    info = ""
                if info != "":
                    info = " |"+info
                if re.match('!\s+A <box> was supposed to be here\.', line) or \
                        re.match('!\s+Infinite glue shrinkage found in a paragraph', line) or \
                        re.match('!\s+Missing \$ inserted\.', line):
                    info = ""
                verbose_msg = ""
                for j in range(1,i):
                    if not re.match("See\s+the\s+\w+\s+manual\s+or\s+\w+\s+Companion\s+for\s+explanation\.|Type\s+[HI]", log_lines[line_nr-1+j]):
                        verbose_msg+=re.sub("^\s*", " ", log_lines[line_nr-1+j])
                    else:
                        break
                if re.match('\s*<(?:inserted text|to be read again|recently read)>', verbose_msg) or \
                        re.match('\s*See the LaTeX manual', verbose_msg) or \
                        re.match('!\s+Infinite glue shrinkage found in a paragraph', line):
                    verbose_msg = ""
                if not re.match('\s*$',verbose_msg):
                    verbose_msg = " |"+verbose_msg

                if last_file == "0":
                    i=-1
                    while True:
                        i+=1
                        try:
                            nline = log_lines[line_nr-1+i]
                            line_m = re.match('<\*>\s+(.*)', nline)
                            if line_m:
                                e_file = line_m.group(1)
                                break
                            elif i>50:
                                e_file="0"
                                break
                        except IndexError:
                            e_file="0"
                            break
                else:
                    e_file = last_file
                if not match:
                    index = len(output_data)
                else:
                    # Find the correct place to put the error message:
                    try:
                        try:
                            prev_element=filter(lambda d: d[1] == e_file and int(d[2]) <= int(input_line), output_data)[-1]
                            index = output_data.index(prev_element)+1
                        except IndexError:
                            prev_element=filter(lambda d: d[1] == e_file and int(d[2]) > int(input_line), output_data)[0]
                            index = output_data.index(prev_element)
                    except IndexError:
                        index = len(output_data)

                output_data.insert(index, [latex_error, e_file, input_line, "0", msg+info+verbose_msg])

    output_data=map(lambda x: "::".join(x), output_data)
    try:
        output_fo=open(output_fname, 'w')
    except IOError:
        print("IOError: cannot open %s file for writting" % output_fname)
        sys.exit(1)
    else:
        output_fo.write('\n'.join(output_data)+'\n')
    finally:
        output_fo.close()


# Main call
if __name__ == '__main__':

    try:
        rewrite_log(sys.argv[1])
    except IOError:
        pass
ftplugin/ATP_files/latextags.py	[[[1
273
#!/usr/bin/python
# -*- coding: utf-8 -*-

import re, optparse, subprocess, os, traceback, sys
from optparse import OptionParser
from time import strftime, localtime
import locale

# Usage:
# latextags.py --files main_file.tex;input_file1.tex;input_file2.tex --auxfile main_file.aux --bibfiles bibfile.bib --dir ./
# --files       : specifies all the tex files in a ";"-separated list to parse (all input files) [this option is necessary]
# --auxfile     : the aux file [this option is necessary]
# --bibfiles    : specifies bibfiles
# --hyperref    : if added \hypertarget{}{} commands are scanned too.
# --cite        : has values: "natbib"/"biblatex"/"" (or not given). It sets apropriate pattern to find all \cite commands.
# --dir         : directory where to put the tag file
# --silent      : be silent
# --servername  : specifies the server name of vim, if given error messages are send to (g)vim
# --progname    : aparentely only two values are supported: "vim"/"gvim".


# ToDoList:
# (1) Use synstack function remotely to get tag_type.
# (2) Scan bib files to get bibkeys (but this might be slow)!
#       this could be written to seprate file.

# OPTIONS:
usage   = "usage: %prog [options]"
parser  = OptionParser(usage=usage)
parser.add_option("--files",    dest="files"    )
parser.add_option("--silent",   dest="silent",          default=False, action="store_true")
parser.add_option("--auxfile",  dest="auxfile"  )
parser.add_option("--hyperref", dest="hyperref",        default=False,  action="store_true")
parser.add_option("--servername", dest="servername",    default=""      )
parser.add_option("--progname", dest="progname",        default="gvim"  )
parser.add_option("--bibfiles", dest="bibfiles",        default=""      )
parser.add_option("--bibtags",  dest="bibtags",         default=False,  action="store_true")
parser.add_option("--bibtags_env",  dest="bibtags_env", default=False,  action="store_true")
parser.add_option("--dir",      dest="directory")
parser.add_option("--cite",     dest="cite",            default="default" )
(options, args) = parser.parse_args()
file_list=options.files.split(";")
bib_list=options.bibfiles.split(";")

# Cite Pattern:
if options.cite == "natbib":
    cite_pattern=re.compile('^(?:[^%]|\\\\%)*\\\\(?:c|C)ite(?:(?:al)?[tp]\*?|year(?:par)?|(?:full)?author\*?|num)?(?:\[.*\])?{([^}]*)}')
elif options.cite == "biblatex":
# there is no pattern for \[aA]utocites, \[tT]extcites, \[sS]martcites,
# \[pP]arencites, \[cC]ites, \footcites, \footcitetexts commands
    cite_pattern=re.compile('^(?:[^%]|\\\\%)*\\\\(?:[cC]ite\*?|[pP]arencite\*?|footcite(?:text)?|[tT]extcite|[sS]martcite|supercite|[aA]utocite\*?|[cC]iteauthor|citetitle\*?|cite(?:year|date|url)|nocite|(?:foot)?fullcite|(?:[vV]ol|fvol|ftvol|[sStTpP]vol)cite(?:\[.*\])?{(?:[^}]*)}|[nN]otecite|[pP]nocite|citename|citefield)(?:\[.*\])?{([^}]*)}')
# (?:[aA]utoc|[tT]extc|[sS]martc|[pP]arenc|[cC]|footc)ites(?:(?:\[.*\]{([^}]*)]))*
else:
    cite_pattern=re.compile('^(?:[^%]|\\\\%)*\\\\(?:no)?cite(?:\[.*\])?{([^}]*)}')

def vim_remote_expr(servername, expr):
# Send <expr> to vim server,

# expr must be well quoted:
#       vim_remote_expr('GVIM', "atplib#callback#TexReturnCode()")
    cmd=[options.progname, '--servername', servername, '--remote-expr', expr]
    subprocess.Popen(cmd)

def get_tag_type(line, match, label):
# Find tag type,

# line is a string, match is an element of a MatchingObject
    tag_type=""
    if label == 'label':
        pat='(?:\\\\hypertarget{.*})?\s*\\\\label'
    else:
        pat='(?:\\\\label{.*})?\s*\\\\hypertarget'
    if re.search('\\\\part{.*}\s*'+pat+'{'+match+'}', line):
        tag_type="part"
    elif re.search('\\\\chapter(?:\[.*\])?{.*}\s*'+pat+'{'+match+'}', line):
        tag_type="chapter"
    elif re.search('\\\\section(?:\[.*\])?{.*}\s*'+pat+'{'+match+'}', line):
        tag_type="section"
    elif re.search('\\\\subsection(?:\[.*\])?{.*}\s*'+pat+'{'+match+'}', line):
        tag_type="subsection"
    elif re.search('\\\\subsubsection(?:\[.*\])?{.*}\s*'+pat+'{'+match+'}', line):
        tag_type="subsubsection"
    elif re.search('\\\\paragraph(?:\[.*\])?{.*}\s*'+pat+'{'+match+'}', line):
        tag_type="paragraph"
    elif re.search('\\\\subparagraph(?:\[.*\])?{.*}\s*'+pat+'{'+match+'}', line):
        tag_type="subparagraph"
    elif re.search('\\\\begin{[^}]*}', line):
        # \label command must be in the same line, 
        # To do: I should add searching in next line too.
        #        Find that it is inside \begin{equation}:\end{equation}.
        type_match=re.search('\\\\begin\s*{\s*([^}]*)\s*}(?:\s*{.*})?\s*(?:\[.*\])?\s*'+pat+'{'+match+'}', line)
        try:
            # Use the last found match (though it should be just one).
            tag_type=type_match.group(len(type_match.groups()))
        except AttributeError:
            tag_type=""
    return tag_type

def find_in_filelist(match, file_dict, get_type=False, type_pattern=None):
# find match in list of files, 

# file_dict is a dictionary with { 'file_name' : file }.
    r_file = ""
    r_type = ""
    for file in file_dict.iterkeys():
        flinenr=1
        for line in file_dict[file]:
            pat_match=re.search(match, line)
            if pat_match:
                r_file=file
                if get_type:
                    r_type=re.match(type_pattern, line).group(1)
                break
            flinenr+=1
    if get_type:
        return [ r_file, flinenr, r_type ]
    else:
        return [ r_file, flinenr ]

def comma_split(arg_list):
    ret_list = []
    for element in arg_list:
        ret_list.extend(element.split(","))
    return ret_list

try:
# Read tex files:
    file_dict={}
# { 'file_name' : list_of_lines }
    for file in file_list:
        try:
            if sys.version_info < (3, 0):
                file_object=open(file, "r")
            else:
                file_object=open(file, "r", errors="replace")
            file_dict[file]=file_object.read().split("\n")
            file_object.close()
        except IOError:
            if options.servername != "":
                vim_remote_expr(options.servername, "atplib#callback#Echo(\"[LatexTags:] file "+file+" not found.\",'echomsg','WarningMsg')")
            file_dict[file]=[]
            pass

# Read bib files:
    if len(bib_list) > 1:
        bib_dict={}
        # { 'bib_name' : list_of_lines } 
        for bibfile in bib_list:
            if sys.version_info < (3, 0):
                bibobject=open(bibfile, "r")
            else:
                bibobject=open(bibfile, "r", errors="replace")
            bib_dict[bibfile]=bibobject.read().split("\n")
            bibobject.close()

# GENERATE TAGS:
# From \label{} and \hypertarget{}{} commands:
    tags=[]
    tag_dict={}
    for file_name in file_list:
        file_ll=file_dict[file_name]
        linenr=0
        p_line=""
        for line in file_ll:
            linenr+=1
            # Find LABELS in the current line:
            matches=re.findall('^(?:[^%]|\\\\%)*\\\\label{([^}]*)}', line)
            for match in matches:
                tag=str(match)+"\t"+file_name+"\t"+str(linenr)
                # Set the tag type:
                tag_type=get_tag_type(line, match, "label")
                if tag_type == "":
                    tag_type=get_tag_type(p_line+line, match, "label")
                tag+=";\"\tinfo:"+tag_type+"\tkind:label"
                # Add tag:
                tags.extend([tag])
                tag_dict[str(match)]=[str(linenr), file_name, tag_type, 'label']
            # Find HYPERTARGETS in the current line:        /this could be switched on/off depending on useage of hyperref/
            if options.hyperref:
                matches=re.findall('^(?:[^%]|\\\\%)*\\\\hypertarget{([^}]*)}', line)
                for match in matches:
                    # Add only if not yet present in tag list:
                    if not str(match) in tag_dict:
                        tag_dict[str(match)]=[str(linenr), file_name, tag_type, 'hyper']
                        tag_type=get_tag_type(line, match, 'hypertarget')
                        if tag_type == "":
                            tag_type=get_tag_type(p_line+line, match, "label")
                        tags.extend([str(match)+"\t"+file_name+"\t"+str(linenr)+";\"\tinfo:"+tag_type+"\tkind:hyper"])
            # Find CITATIONS in the current line:
            if options.bibtags and not options.bibtags_env:
                # There is no support for \citealias comman in natbib.
                # complex matches are slower so I should pass an option if one uses natbib.
                matches=re.findall(cite_pattern, line)
                matches=comma_split(matches)
                for match in matches:
                    if not str(match) in tag_dict:
                        if len(bib_list) == 1:
                            tag=str(match)+"\t"+bib_list[0]+"\t/"+match+"/;\"\tkind:cite"
                            tag_dict[str(match)]=['', bib_list[0], '', 'cite']
                            tags.extend([tag])
                        elif len(bib_list) > 1:
                            bib_file=""
                            [ bib_file, bib_linenr, bib_type ] = find_in_filelist(re.compile(str(match)), bib_dict, True, re.compile('\s*@(.*){'))
                            if bib_file != "":
#                             tag=str(match)+"\t"+bib_file+"\t/"+match+"/;\"\tkind:cite\tinfo:"+bib_type
                                tag=str(match)+"\t"+bib_file+"\t"+str(bib_linenr)+";\"\tkind:cite\tinfo:"+bib_type
                                tag_dict[str(match)]=['', bib_file, bib_type, 'cite']
                                tags.extend([tag])
            if options.bibtags and options.bibtags_env:
                matches=re.findall(cite_pattern, line)
                matches=comma_split(matches)
                for match in matches:
                    if not str(match) in tag_dict:
                        [ r_file, r_linenr ] = find_in_filelist(re.compile("\\\\bibitem(?:\s*\[.*\])?\s*{"+str(match)+"}"), file_dict)
                        tag=str(match)+"\t"+r_file+"\t"+str(r_linenr)+";\"\tkind:cite"
                        tag_dict[str(match)]=[str(r_linenr), r_file, '', 'cite']
                        tags.extend([tag])
            p_line=line

# From aux file:
    ioerror=False
    try:
        if sys.version_info < (3, 0):
            auxfile=open(options.auxfile, "r")
        else:
            auxfile=open(options.auxfile, "r", errors="replace")
        for line in auxfile:
            if re.match('\\\\newlabel{[^}]*}{{[^}]*}', line):
                [label, counter]=re.match('\\\\newlabel{([^}]*)}{{([^}]*)}', line).group(1,2)
                counter=re.sub('{', '', counter)
                if re.search('[0-9.]+', counter):
                    # Arabic Numbered counter:
                    counter=re.search('[0-9.]+', counter).group(0)
                elif re.search('[ivx]+\)?$', counter):
                    # Roman numberd counter:
                    counter=re.search('\(?([ivx]+)\)?$', counter).group(1)
                else:
                    counter=""
                try:
                    [linenr, file, tag_type, kind]=tag_dict[label]
                except KeyError:
                    [linenr, file, tag_type, kind]=["no_label", "no_label", "", ""]
                except ValueError:
                    [linenr, file, tag_type, kind]=["no_label", "no_label", "", ""]
                if linenr != "no_label" and counter != "":
                    tags.extend([str(counter)+"\t"+file+"\t"+linenr+";\"\tinfo:"+tag_type+"\tkind:"+kind])
        auxfile.close()
    except IOError:
        ioerror=True
        pass

# SORT (vim works faster when tag file is sorted) AND WRITE TAGS
    time=strftime("%a, %d %b %Y %H:%M:%S +0000", localtime())
    tags_sorted=sorted(tags, key=str.lower)
    tags_sorted=['!_TAG_FILE_SORTED\t1\t/'+time]+tags_sorted
    os.chdir(options.directory)
    tag_file = open("tags", 'w')
    tag_file.write("\n".join(tags_sorted))
    tag_file.close()

# Communicate to Vim:
    if not options.silent:
        if options.servername != "":
            vim_remote_expr(options.servername, "atplib#callback#Echo(\"[LatexTags:] tags file written.\",'echo','')")
        if ioerror and options.servername:
            vim_remote_expr(options.servername, "atplib#callback#Echo(\"[LatexTags:] no aux file.\",'echomsg', 'WarningMsg')")
except Exception:
    # Send errors to vim is options.servername is non empty.
    error_str=re.sub("'", "''",re.sub('"', '\\"', traceback.format_exc()))
    if options.servername != "":
        vim_remote_expr(options.servername, "atplib#callback#Echo(\"[ATP:] error in latextags.py, catched python exception:\n"+error_str+"\",'echo','ErrorMsg')")
    else:
        print(error_str)
ftplugin/ATP_files/makelatex.py	[[[1
558
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Marcin Szamotulski
# Date: 23 IV 2011
# This file is a part of AutomaticTexPlugin plugin for Vim.
# It is distributed under General Public Licence v3 or higher.
# 
# Note: this script, in order to work well, needs a high value of
# max_print_line (ATP uses 2000) in order to not break log messages into lines.
# This can be passed using the --env switch. (On the command line it is used in
# this form: max_print_line=2000 latex .... )

# import signal, os
# def handler(signum, frame):


import shutil, os.path, re, optparse, subprocess, traceback, psutil
import tempfile, os, atexit, sys

import latex_log

from optparse import OptionParser
from os import getcwd
from signal import SIGKILL
from collections import deque

usage   = "usage: %prog [options]"
parser  = OptionParser(usage=usage)

parser.add_option("--texfile",          dest="texfile"                                                  )
parser.add_option("--bufnr",            dest="bufnr"                                                    )
parser.add_option("--cmd",              dest="cmd",             default="pdflatex"                      )
parser.add_option("--output-format",    dest="output_format",   default="pdf"                           )
parser.add_option("--bibcmd",           dest="bibcmd",          default="bibtex"                        )
parser.add_option("--tex-options",      dest="tex_options",     default=""                              )
parser.add_option("--outdir",           dest="outdir"                                                   )
parser.add_option("--logdir",           dest="logdir"                                                   )
parser.add_option("--tempdir",          dest="tempdir",         default=""                              )
parser.add_option("--progname",         dest="progname",        default="gvim"                          )
parser.add_option("--servername",       dest="servername"                                               )
parser.add_option("--viewer",           dest="viewer",          default="xpdf"                          )
parser.add_option("--xpdf-server",      dest="xpdf_server",                                             )
parser.add_option("--viewer-options",   dest="viewer_opt",      default="",                             )
parser.add_option("--start",            dest="start",           default=0,              type="int"      )
parser.add_option("--keep",             dest="keep",            default="aux,toc,bbl,ind,pdfsync,synctex.gz")
parser.add_option("--reload-viewer",    dest="reload_viewer",   default=False,          action="store_true")
parser.add_option("--reload-on-error",  dest="reload_on_error", default=False,          action="store_true")
parser.add_option("--bibliographies",   dest="bibliographies",  default="",                             )
parser.add_option("--verbose",          dest="verbose",         default="silent"                        )
parser.add_option("--no-callback",      dest="callback",        default=True,           action="store_false")
# This is not yet used:
parser.add_option("--force",            dest="force",           default=False,          action="store_true")
parser.add_option("--env",              dest="env",             default=""                              )


(options, args) = parser.parse_args()

debugfile=os.path.join(options.logdir, "makelatex.log")
debug_file=open(debugfile, "w")

texfile = options.texfile
bufnr   = options.bufnr
basename = os.path.splitext(os.path.basename(texfile))[0]
texfile_dir = os.path.dirname(texfile)
if options.tempdir == "":
    options.tempdir = os.path.join(texfile_dir,".tmp")
logfile = basename+".log"
debug_file.write("logfile="+logfile+"\n")
auxfile = basename+".aux"
bibfile = basename+".bbl"
idxfile = basename+".idx"
indfile = basename+".ind"
tocfile = basename+".toc"
loffile = basename+".lof"
lotfile = basename+".lot"
thmfile = basename+".thm"

if not os.path.exists(options.tempdir):
        # This is the main tmp dir (./.tmp) 
        # it will not be deleted by this script
        # as another instance might be using it.
        # it is removed by Vim on exit.
    os.mkdir(options.tempdir)
tmpdir  = tempfile.mkdtemp(dir=options.tempdir,prefix="")

# List of pids runing.
pids    = []
# Cleanup on exit:
def cleanup(debug_file, tmpdir, pids):
    debug_file.close()
    shutil.rmtree(tmpdir)
# Will this function be called when scripts get SIGKILL, if yes
# then this code might be helpful:
# THIS NEEDS sys MODULE AND SIGKILL from SIGNAL MODULE
#     for pid in pids:
#         try:
#             os.kill(pid,SIGKILL)
#         except OSError:
#             # No such process error.
#             pass
atexit.register(cleanup, debug_file, tmpdir, pids)

# FILTER:
nonempty = lambda x: (re.match('\s*$', x) is None)

servername      = options.servername
debug_file.write("SERVERNAME="+servername+"\n")
progname        = options.progname
debug_file.write("PROGNAME="+progname+"\n")
cmd		= options.cmd
debug_file.write("CMD="+cmd+"\n")
tex_options	= options.tex_options
debug_file.write("TEX_OPTIONS="+tex_options+"\n")
output_format   = options.output_format
if output_format == "pdf":
    output_ext = ".pdf"
else:
    output_ext = ".dvi"
output_fp       = os.path.join(texfile_dir,basename+output_ext)
debug_file.write("OUTPUT_FORMAT="+output_format+"\n")
bibcmd		= options.bibcmd
debug_file.write("BIBCMD="+bibcmd+"\n")
biber=False
if re.search(bibcmd, '^\s*biber'):
    biber=True
debug_file.write("BIBER="+str(biber)+"\n")
bibliographies  = options.bibliographies.split(",")
bibliographies  = list(filter(nonempty, bibliographies))

tex_options     = list(filter(nonempty,re.split('\s*,\s*',options.tex_options)))
debug_file.write("TEX_OPTIONS_LIST="+str(tex_options)+"\n")

outdir		= options.outdir
debug_file.write("OUTDIR="+outdir+"\n")
force		= options.force
debug_file.write("FORCE="+str(force)+"\n")
start           = options.start
viewer          = options.viewer
XpdfServer      = options.xpdf_server
reload_viewer   = options.reload_viewer
reload_on_error = options.reload_on_error
viewer_rawopt   = re.split('\s*;\s*', options.viewer_opt)
viewer_it       = list(filter(nonempty,viewer_rawopt))
viewer_opt      =[]
for opt in viewer_it:
    viewer_opt.append(opt)
viewer_rawopt   = viewer_opt
if viewer == "xpdf" and XpdfServer != None:
    viewer_opt.extend(["-remote", XpdfServer])
keep            = options.keep.split(',')
keep            = list(filter(nonempty, keep))
debug_file.write("KEEP="+str(keep)+"\n")

if len(options.env)>0:
    env = list(map(lambda x: re.split('\s*=\s*', x), list(filter(nonempty, re.split('\s*;\s*',options.env)))))
else:
    env = []


# RUN NUMBER
run   = 0
# BOUND (do not run pdflatex more than this) 
# echoerr in Vim if bound is reached.
bound = 6

# FUNCTIONS

def vim_remote_expr(servername, expr):
    # Send <expr> to vim server,

    # expr must be well quoted:
    #       vim_remote_expr('GVIM', "atplib#CatchStatus()")
    # (this is the only way it works)
    #     print("VIM_REMOTE_EXPR "+str(expr))
    if not options.callback:
        return
    cmd=[progname, '--servername', servername, '--remote-expr', expr]
    try:
        devnull=open(os.devnull, "w+")
    except IOError:
        print("IOError: cannot open os.devnull")
        sys.exit(1)
    else:
        subprocess.Popen(cmd, stdout=devnull, stderr=subprocess.STDOUT).wait()
    finally:
        devnull.close()

def latex_progress_bar(cmd):
    # Run latex and send data for progress bar,

    debug_file.write("RUN "+str(run)+" CMD"+str(cmd)+"\n")

    child = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    pid   = child.pid
    pids.append(pid)

    vim_remote_expr(servername, "atplib#callback#LatexPID("+str(pid)+")")
    stack = deque([])
    while True:
        try:
            out = child.stdout.read(1).decode(errors="replace")
        except UnicodeDecodeError:
            debug_file.write("UNICODE DECODE ERROR:\n")
            debug_file.write(child.stdout.read(1).encode(errors="ignore"))
            debug_file.write("\n")
            out = ""
        if out == '' and child.poll() != None:
            break
        if out != '':
            stack.append(out)

            if len(stack)>10:
                stack.popleft()
            match = re.match('\[(\n?\d(\n|\d)*)({|\])',''.join(stack))
            if match:
                vim_remote_expr(servername, "atplib#callback#ProgressBar("+match.group(1)[match.start():match.end()]+","+str(pid)+","+str(bufnr)+")")
    child.wait()
    vim_remote_expr(servername, "atplib#callback#ProgressBar('end',"+str(pid)+","+str(bufnr)+")")
    vim_remote_expr(servername, "atplib#callback#PIDsRunning(\"b:atp_LatexPIDs\")")
    return child

def xpdf_server_file_dict():
    # Make dictionary of the type { xpdf_servername : [ file, xpdf_pid ] },

    # to test if the server host file use:
    # basename(xpdf_server_file_dict().get(server, ['_no_file_'])[0]) == basename(file)
    # this dictionary always contains the full path (Linux).
    # TODO: this is not working as I want to:
    #    when the xpdf was opened first without a file it is not visible in the command line
    #    I can use 'xpdf -remote <server> -exec "run('echo %f')"'
    #    where get_filename is a simple program which returns the filename. 
    #    Then if the file matches I can just reload, if not I can use:
    #          xpdf -remote <server> -exec "openFile(file)"
    ps_list=psutil.get_pid_list()
    server_file_dict={}
    for pr in ps_list:
        try:
            name=psutil.Process(pr).name
            cmdline=psutil.Process(pr).cmdline
            if name == 'xpdf':
                try:
                    ind=cmdline.index('-remote')
                except:
                    ind=0
                if ind != 0 and len(cmdline) >= 1:
                    server_file_dict[cmdline[ind+1]]=[cmdline[len(cmdline)-1], pr]
        except psutil.error.NoSuchProcess:
            pass
        except psutil.error.AccessDenied:
            pass
    return server_file_dict

def reload_xpdf():
    # Reload xpdf if asked,

    if re.search(viewer, '^\s*xpdf\e') and reload_viewer:
        cond=xpdf_server_file_dict().get(XpdfServer, ['_no_file_']) != ['_no_file_']
        if cond and ( reload_on_error or latex.returncode == 0 or bang ):
            debug_file.write("reloading Xpdf\n")
            cmd=['xpdf', '-remote', XpdfServer, '-reload']
            devnull=open(os.devnull, "w+")
            subprocess.Popen(cmd, stdout=devnull, stderr=subprocess.STDOUT)
            devnull.close()

def copy_back_output(tmpdir):
    # Copy pdf(dvi) and (aux) files back to working directory,

    # aux file is copied also to _aux file used by ATP.
    os.chdir(tmpdir)
    if os.path.exists(basename+output_ext):
        shutil.copy(basename+output_ext, texfile_dir)
    if os.path.exists(basename+".aux"):
        shutil.copy(basename+".aux", texfile_dir)
        shutil.copy(basename+".aux", os.path.join(texfile_dir, basename+"._aux"))
    os.chdir(texfile_dir)

def copy_back(tmpdir, latex_returncode):

    os.chdir(tmpdir)
    if not latex_returncode or not os.path.exists(os.path.join(texfile_dir, auxfile)):
        ext_list=list(keep)
    else:
        ext_list=list(filter(lambda x: x != 'aux', keep))
    for ext in ext_list:
        file_cp=basename+"."+ext
        if os.path.exists(file_cp):
            shutil.copy(file_cp, texfile_dir)
    os.chdir(texfile_dir)

try:
    # Send pid to ATP:
    vim_remote_expr(servername, "atplib#callback#PythonPID("+str(os.getpid())+")")
    cwd = getcwd()
    os.chdir(texfile_dir)

    # Note always run first time.
    # this ensures that the aux, ... files are uptodate.

    # COPY FILES TO TEMP DIR
    debug_file.write("TMPDIR="+tmpdir+"\n")
    tmplog  = os.path.join(tmpdir,basename+".log")
    debug_file.write("TMPLOG="+tmplog+"\n")
    tmpaux  = os.path.join(tmpdir,basename+".aux")

    for ext in filter(lambda x: x != 'log', keep):
        file_cp=basename+"."+ext
        if os.path.exists(file_cp):
            shutil.copy(file_cp, tmpdir)

    tempdir_list = os.listdir(tmpdir)
    debug_file.write("ls tmpdir "+str(tempdir_list)+"\n")
    for bib in bibliographies:
        if os.path.exists(os.path.join(texfile_dir,os.path.basename(bib))):
            os.symlink(os.path.join(texfile_dir,os.path.basename(bib)),os.path.join(tmpdir,os.path.basename(bib)))

    # SET ENVIRONMENT
    for var in env:
        os.putenv(var[0], var[1])

    # SOME VARIABLES
    did_bibtex      = False
    did_makeidx     = False

    # WE RUN FOR THE FIRST TIME:
    # Set Environment:
    if len(env) > 0:
        for var in env:
            os.putenv(var[0], var[1])

    output_exists=os.path.exists(os.path.join(texfile_dir,basename+output_ext))
    debug_file.write("OUTPUT_EXISTS="+str(output_exists)+":"+os.path.join(texfile_dir,basename+output_ext)+"\n")
    latex=latex_progress_bar([cmd, '-interaction=nonstopmode', '-output-directory='+tmpdir]+tex_options+[texfile])
    run  += 1
    latex.wait()
    vim_remote_expr(servername, "atplib#callback#TexReturnCode('"+str(latex.returncode)+"')")
    os.chdir(tmpdir)
    if not output_exists:
        copy_back_output(tmpdir)
        reload_xpdf()

    # AFTER FIRST TIME LOG FILE SHOULD EXISTS:
    if os.path.isfile(tmplog):

        need_runs = [0]

        if sys.version_info < (3, 0):
            log_file  = open(tmplog, "r")
        else:
            log_file  = open(tmplog, "r", errors="replace")
        log       = log_file.read()
        log_file.close()
        log_list=re.findall('(undefined references)|(Citations undefined)|(There were undefined citations)|(Label\(s\) may have changed)|(Writing index file)|(run Biber on the file)',log)
        citations       =False
        labels          =False
        makeidx         =False
        for el in log_list:
            if el[0] != '' or el[1] != '' or el[2] != '':
                citations       =True
                if biber:
                    need_runs.append(1)
                else:
                    # Bibtex:
                    need_runs.append(2)
            if el[3] != '':
                labels          =True
            if el[4] != '':
                makeidx         =True
                need_runs.append(1)

        debug_file.write("citations="+str(citations)+"\n")
        debug_file.write("labels="+str(labels)+"\n")
        debug_file.write("makeidx="+str(makeidx)+"\n")

        # Scan for openout files to know if we are makeing: toc, lot, lof, thm
        openout_list=re.findall("\\\\openout\d+\s*=\s*`\"?([^'\"]*)\"?'",log)
        toc     =False
        lot     =False
        lof     =False
        thm     =False
        loa     =False
        for el in openout_list:
            if re.search('\.toc$',el):
                toc=True
                need_runs.append(1)
                # We need only one more run, because of the 0-run.
            if re.search('\.lof$',el):
                lof=True
                need_runs.append(1)
            if re.search('\.lot$',el):
                lot=True
                need_runs.append(1)
            if re.search('\.thm$',el):
                thm=True
                need_runs.append(1)
            if re.search('\.loa',el):
                loa=True
                need_runs.append(1)

        debug_file.write("A0 need_runs="+str(need_runs)+"\n")

        # Aux file should be readable (we always run for the first time)
        #     auxfile_readable = os.path.isfile(auxfile)
        idxfile_readable = os.path.isfile(idxfile)
        tocfile_readable = os.path.isfile(tocfile)
        loffile_readable = os.path.isfile(loffile)
        lotfile_readable = os.path.isfile(lotfile)
        thmfile_readable = os.path.isfile(thmfile)

        try:
            if sys.version_info < (3, 0):
                aux_file=open(tmpaux, "r")
            else:
                aux_file=open(tmpaux, "r", errors="replace")
            aux=aux_file.read()
            aux_file.close()
        except IOError:
            aux=""
            pass
        bibtex=re.search('\\\\bibdata\s*{', aux)
        # This can be used to make it faster and use the old bbl file.
        # For this I have add a switch (bang).
        #         bibtex=re.search('No file '+basename+'\.bbl\.', log)
        if not bibtex:
            # Then search for biblatex package. Alternatively, I can search for biblatex messages in log file.
            if sys.version_info < (3, 0):
                texfile_ob = open(texfile, 'r')
            else:
                texfile_ob = open(texfile, 'r', errors='replace')
            for line in texfile_ob:
                if re.match('[^%]*\\\\usepackage\s*(\[[^]]*\])?\s*{(\w\|,)*biblatex',line):
                    bibtex=True
                    break
                elif re.search('\\\\begin\s*{\s*document\s*}',line):
                    break
            texfile_ob.close()
        debug_file.write("BIBTEX="+str(bibtex)+"\n")

        # I have to take the second condtion (this is the first one):
        condition = citations or labels or makeidx or run <= max(need_runs)
        debug_file.write(str(run)+"condition="+str(condition)+"\n")

        # HERE IS THE MAIN LOOP:
        # I guess some of the code done above have to be put inside the loop.
        # Maybe it would be nice to make functions from some parts of the code.
        while condition:
            if run == 1:
                # BIBTEX
                if bibtex:
                    bibtex      = False
                    did_bibtex  = True
                    os.chdir(tmpdir)
                    if re.search(bibcmd, '^\s*biber'):
                        auxfile = basename
                    bibtex=subprocess.Popen([bibcmd, auxfile], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
                    vim_remote_expr(servername, "atplib#callback#BibtexPID('"+str(bibtex.pid)+"')")
                    vim_remote_expr(servername, "atplib#callback#redrawstatus()")
                    pids.append(bibtex.pid)
                    bibtex.wait()
                    vim_remote_expr(servername, "atplib#callback#PIDsRunning(\"b:atp_BibtexPIDs\")")
                    bibtex_output=re.sub('"', '\\"', bibtex.stdout.read().decode())
                    bibtex_returncode=bibtex.returncode
                    vim_remote_expr(servername, "atplib#callback#BibtexReturnCode('"+str(bibtex_returncode)+"',\""+str(bibtex_output)+"\")")
                    os.chdir(texfile_dir)
                # MAKEINDEX
                if makeidx:
                    makeidx=False
                    did_makeidx=True
                    os.chdir(tmpdir)
                    index=subprocess.Popen(['makeindex', idxfile], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
                    vim_remote_expr(servername, "atplib#callback#MakeindexPID('"+str(index.pid)+"')")
                    vim_remote_expr(servername, "atplib#callback#redrawstatus()")
                    pids.append(index.pid)
                    index.wait()
                    vim_remote_expr(servername, "atplib#callback#PIDsRunning(\"b:atp_MakeindexPIDs\")")
                    makeidx_output=re.sub('"', '\\"', index.stdout.read().decode())
                    index_returncode=index.returncode
                    vim_remote_expr(servername, "atplib#callback#MakeidxReturnCode('"+str(index_returncode)+"',\""+str(makeidx_output)+"\")")
                    os.chdir(texfile_dir)

            # LATEX
            os.chdir(texfile_dir)
            latex=latex_progress_bar([cmd, '-interaction=nonstopmode', '-output-directory='+tmpdir]+tex_options+[texfile])
            run  += 1
            latex.wait()
            vim_remote_expr(servername, "atplib#CatchStatus('"+str(latex.returncode)+"')")
            copy_back_output(tmpdir)
            reload_xpdf()

            #CONDITION
            try:
                if sys.version_info < (3, 0):
                    log_file=open(tmplog, "r")
                else:
                    log_file=open(tmplog, "r", errors="replace")
                log=log_file.read()
                log_file.close()
            except IOError:
                log=""
                pass

            # Citations undefined|Label(s) may have changed
            log_list=re.findall('(undefined references)|(Citations undefined)|(Label\(s\) may have changed)',log)
            citations       =False
            labels          =False
            for el in log_list:
                if el[0] != '' or el[1] != '':
                    citations       =True
                if el[2] != '':
                    labels          =True
            debug_file.write(str(run)+"citations="+str(citations)+"\n")
            debug_file.write(str(run)+"labels="+str(labels)+"\n")
            debug_file.write(str(run)+"makeidx="+str(makeidx)+"\n")

            debug_file.write(str(run)+"need_runs="+str(need_runs)+"\n")

            condition = ( (citations and run <= max(need_runs)) or labels or makeidx or run <= max(need_runs) ) and run <= bound
            debug_file.write(str(run)+"condition="+str(condition)+"\n")

    # Start viewer: (reloading xpdf is done after each compelation) 
    if re.search(viewer, '^\s*xpdf\e') and reload_viewer:
        # The condition tests if the server XpdfServer is running
        xpdf_server_dict=xpdf_server_file_dict()
        cond = xpdf_server_dict.get(XpdfServer, ['_no_file_']) != ['_no_file_']
        if start == 1:
            debug_file.write("Starting Xpdf\n")
            run=['xpdf']
            run.extend(viewer_opt)
            run.append(output_fp)
            subprocess.Popen(run)
    else:
        if start >= 1:
            debug_file.write("Starting "+str(viewer))
            run=[viewer]
            run.extend(viewer_opt)
            run.append(output_fp)
            devnull=open(os.devnull, "w+")
            subprocess.Popen(run, stdout=devnull, stderr=subprocess.STDOUT)
            devnull.close()
        if start == 2:
            debug_file.write("SyncTex with "+str(viewer))
            vim_remote_expr(servername, "atplib#SyncTex()")
    copy_back(tmpdir, latex.returncode)
except Exception:
    error_str=re.sub("'", "''",re.sub('"', '\\"', traceback.format_exc()))
    traceback.print_exc(None, debug_file)
    vim_remote_expr(servername, "atplib#callback#Echo(\"[ATP:] error in makelatex.py, catched python exception:\n"+error_str+"[ATP info:] this error message is recorded in makelatex.log under g:atp_TempDir\",'echo','ErrorMsg')")

# Rewrite the LaTeX log file.
latex_log.rewrite_log(logfile, check_path=True, project_dir=texfile_dir, project_tmpdir=tmpdir)

debug_file.write("PIDS="+str(pids))
vim_remote_expr(servername, "atplib#callback#Echo('[ATP:] MakeLatex finished.', 'echomsg', 'Normal')")
if did_bibtex and bibtex_returncode != 0:
    vim_remote_expr(servername, "atplib#callback#Echo('[MakeLatex:] bibtex returncode "+str(bibtex_returncode)+".', 'echo', 'Normal')")
if did_makeidx and index_returncode != 0:
    vim_remote_expr(servername, "atplib#callback#Echo('[MakeLatex:] makeidx returncode "+str(index_returncode)+".', 'echo', 'Normal')")
vim_remote_expr(servername, "atplib#callback#CallBack('"+str(bufnr)+"','"+str(options.verbose)+"','COM','"+str(did_bibtex)+"','"+str(did_makeidx)+"')")
sys.exit(latex.returncode)
ftplugin/ATP_files/mappings.vim	[[[1
1373
" Author:	Marcin Szmotulski
" Description:  This file contains mappings defined by ATP.
" Note:		This file is a part of Automatic Tex Plugin for Vim.
" Language:	tex
" Last Change: Thu Apr 26, 2012 at 20:40:41  +0100

" Add maps, unless the user didn't want them.
if exists("g:no_plugin_maps") && g:no_plugin_maps ||
	    \ exists("g:no_atp_maps") 	&& g:no_atp_maps ||
	    \ exists("g:no_".&l:filetype."_maps") && g:no_{&l:filetype}_maps
    finish
endif
" SOME VARIABLES: {{{1
" Try to be cpoptions compatible:
if &l:cpoptions =~# "B"
    let s:backslash="\\"
    let s:bbackslash="\\\\"
else
    let s:backslash="\\\\"
    let s:bbackslash="\\\\\\\\"
endif

if g:atp_mapNn
    call atplib#search#ATP_ToggleNn(1,"on")
endif

" DICTIONARY MAP: {{{1
if !hasmapto("<Plug>Dictionray")
    nmap <buffer> <silent> =d <Plug>Dictionary
endif

" REPLACE: {{{1 
" Replace map (is not working -> use :Repace command)
" if !g:atp_VimCompatible && !hasmapto("<Plug>Replace")
"     nnoremap <buffer> <silent> r <Plug>Replace
" endif
nn <buffer> <silent> r :<C-U>call <SID>Replace("<SID>")<CR>
nn <buffer> <silent> <SID>InputRestore  :call inputrestore()<CR>
function! <SID>Replace(sid,...) "{{{2
    " It will not work with <:> since with the default settings "normal %" is not
    " working with <:>, possibly because g:atp_bracket_dict doesn't contain this
    " pair.
    let sid = eval('"\'.a:sid.'"')
    if !a:0
	let char =  nr2char(getchar())
    else
	let char = a:1
    endif
    let g:char = char
    let f_char = getline(line("."))[col(".")-1]
    let g:f_char = f_char
    if f_char =~ '^[(){}\[\]]$'
	if f_char =~ '^[({\[]$'
	    let bracket_dict = { '{' : '}',
			\  '(' : ')',
			\  '[' : ']',}
	else
	    let bracket_dict = { '}' : '{',
			\  ')' : '(',
			\  ']' : '[',}
	endif
	let c_bracket = get(bracket_dict,char, "")
	if c_bracket == ""
	    exec printf("nn <SID>ReplaceCmd %sr%s", (v:count>=1 ? v:count : ""), char)
	    call inputsave()
	    call feedkeys(sid."ReplaceCmd". sid."InputRestore")
	    return
	endif
	let [b_line, b_col] = [line("."), col(".")]
	exe "normal! %"
	let [e_line, e_col] = [line("."), col(".")]
	if b_line == e_line && b_col == e_col
	    exec printf("nn <SID>ReplaceCmd %sr%s", (v:count>=1 ? v:count : ""), char)
	    call inputsave()
	    call feedkeys(sid."ReplaceCmd". sid."InputRestore")
	    return
	endif

	call cursor(b_line, b_col)
	exe "normal! r".char

	call cursor(e_line, e_col)
	exe "normal! r".c_bracket
	call cursor(b_line, b_col)
	return
    else
	exec  printf("nn <SID>ReplaceCmd %sr%s", (v:count>=1 ? v:count : ""), char)
	call inputsave()
	call feedkeys(sid."ReplaceCmd". sid."InputRestore")
	call cursor(line("."), col("."))
    endif
endfunction "}}}2

" UNWRAP MAP: {{{1
if !hasmapto("<Plug>Unwrap")
    nmap <buffer> <silent> <LocalLeader>u <Plug>Unwrap
endif

" CC IMAP: {{{1
" <c-c> in insert mode doesn't trigger InsertLeave autocommands
" this fixes this.
if g:atp_IMapCC
    imap <silent> <buffer> <C-c> <C-[>
endif

" NOT A COMMENT PATTERN CMAP: {{{1
exe "cmap <buffer> <expr> <M-c> '^'.(getcmdline() =~ '\\\\v' ? '' : '".s:backslash."').'([^'.(getcmdline() =~ '\\\\v' ? '".s:backslash."' : '').'%]'.(getcmdline() =~ '\\\\v' ? '' : '".s:backslash."').'\\|".s:bbackslash."'.(getcmdline() =~ '\\\\v' ? '".s:backslash."' : '').'%'.(getcmdline() =~ '\\\\v' ? '' : '".s:backslash."').')*".s:backslash."zs'"
" SPECIAL SPACE CMAP: {{{1
if has("gui")
    if &l:cpoptions =~# "B"
	if g:atp_cmap_space
	    cmap <buffer> <expr> <space> ( g:atp_cmap_space && getcmdtype() =~ '[/?]' && getcmdline() !~ '\\v' ? '\_s\+' : ( getcmdline() =~ '\\v' ? '\_s+' : ' ' ) )
	endif
	cmap <expr> <buffer> <C-Space> ( getcmdtype() =~ '[/?]' && getcmdline() !~ '\\v' ? '\_s\+' : ( getcmdline() =~ '\\v' ? '\_s+' : ' ' ) ) 
	cmap <expr> <buffer> <C-_> ( getcmdtype() =~ '[/?]' && getcmdline() !~ '\\v' ? '\_s\+' : ( getcmdline() =~ '\\v' ? '\_s+' : ' ' ) )
    else
	if g:atp_cmap_space
	    cmap <buffer> <expr> <space> ( g:atp_cmap_space && getcmdtype() =~ '[/?]' && getcmdline() !~ '\\v' ? '\\_s\\+' : ( getcmdline() =~ '\\v' ? '\\_s+' : ' ' ) )
	endif
	cmap <expr> <buffer> <C-Space> ( getcmdtype() =~ '[/?]' && getcmdline() !~ '\\v' ? '\\_s\\+' : ( getcmdline() =~ '\\v' ? '\\_s+' : ' ' ) )
	cmap <expr> <buffer> <C-_> ( getcmdtype() =~ '[/?]' && getcmdline() !~ '\\v' ? '\\_s\\+' : ( getcmdline() =~ '\\v' ? '\\_s+' : ' ' ) )
    endif
else
    if &l:cpoptions =~# "B"
	if g:atp_cmap_space
	    cmap <buffer> <expr> <space> ( g:atp_cmap_space && getcmdtype() =~ '[/?]' && getcmdline() !~ '\\v' ? '\_s\+' : ( getcmdline() =~ '\\v' ? '\_s+' : ' ' ) )
	endif
	cmap <expr> <buffer> <C-@> ( getcmdtype() =~ '[/?]' && getcmdline() !~ '\\v' ? '\_s\+' : ( getcmdline() =~ '\\v' ? '\_s+' : ' ' ) )
	cmap <expr> <buffer> <C-_> ( getcmdtype() =~ '[/?]' && getcmdline() !~ '\\v' ? '\_s\+' : ( getcmdline() =~ '\\v' ? '\_s+' : ' ' ) )
    else
	if g:atp_cmap_space
	    cmap <buffer> <expr> <space> ( g:atp_cmap_space && getcmdtype() =~ '[?\/]' && getcmdline() !~ '\\v' ? '\\_s\\+' : ( getcmdline() =~ '\\v' ? '\\_s+' : ' ' ) )
	endif
	cmap <expr> <buffer> <C-@> ( g:atp_cmap_space && getcmdtype() =~ '[?\/]' && getcmdline() !~ '\\v' ? '\\_s\\+' : ( getcmdline() =~ '\\v' ? '\\_s+' : ' ' ) )
	cmap <expr> <buffer> <C-_> ( g:atp_cmap_space && getcmdtype() =~ '[?\/]' && getcmdline() !~ '\\v' ? '\\_s\\+' : ( getcmdline() =~ '\\v' ? '\\_s+' : ' ' ) )
" OK
    endif
endif
if maparg("<F2>", "n") == ""
    nmap <buffer> <F2>	:echo ATP_ToggleSpace()<CR>
endif

" COMMANDS: font preview, open fd file, close last: environment, bracket {{{1
command! -buffer -bang -nargs=* FontSearch	:call atplib#fontpreview#FontSearch(<q-bang>, <f-args>)
command! -buffer -bang -nargs=* FontPreview	:call atplib#fontpreview#FontPreview(<q-bang>,<f-args>)
command! -buffer -nargs=1 -complete=customlist,atplib#Fd_completion OpenFdFile	:call atplib#tools#OpenFdFile(<f-args>) 
command! -buffer -nargs=* CloseLastEnvironment	:call atplib#complete#CloseLastEnvironment(<f-args>)
command! -buffer 	  CloseLastBracket	:call atplib#complete#CloseLastBracket()

" SECTION MOTION MAPS: {{{1
if !hasmapto("\"SSec") && !hasmapto("'SSec")
    exe "nmap <buffer> <silent>	".g:atp_goto_section_leader."S		:<C-U>keepjumps exe v:count1.\"SSec\"<CR>"
endif
if !hasmapto("\"Sec") && !hasmapto("'Sec")
    exe "nmap <buffer> <silent>	".g:atp_goto_section_leader."s		:<C-U>keepjumps exe v:count1.\"Sec\"<CR>"
endif
if !hasmapto("\"Chap") && !hasmapto("'Chap")
    exe "nmap <buffer> <silent>	".g:atp_goto_section_leader."c		:<C-U>keepjumps exe v:count1.\"Chap\"<CR>"
endif
if !hasmapto("\"Part") && !hasmapto("'Part")
    exe "nmap <buffer> <silent>	".g:atp_goto_section_leader."p		:<C-U>keepjumps exe v:count1.\"Part\"<CR>"
endif

" SYNCTEX MAPS: {{{1
if !hasmapto("<Plug>SyncTexKeyStroke", "n")
    nmap <buffer> <silent> <LocalLeader>f	<Plug>SyncTexKeyStroke
endif
if !hasmapto("<Plug>SyncTexLKeyStroke", "n")
    nmap <buffer> <silent> <LocalLeader>F	<Plug>SyncTexLKeyStroke
endif
if !hasmapto("<LeftMouse><Plug>SyncTexMouse", "n")
    nmap <buffer> <S-LeftMouse> 		<LeftMouse><Plug>SyncTexMouse
endif

" COMMENT LINES: {{{1
if g:atp_MapCommentLines    
    if !hasmapto("<Plug>CommentLines", "n")
	exe "nmap <buffer> <silent> ".g:atp_map_Comment."	<Plug>CommentLines"
    endif
    if !hasmapto("<Plug>CommentLines", "v")
	exe "vmap <buffer> <silent> ".g:atp_map_Comment."	<Plug>CommentLines"
    endif
"     if !hasmapto("<Plug>UnCommentLines", "n")
" 	exe "nmap <buffer> <silent> ".g:atp_map_UnComment."	<Plug>UnCommentLines"
"     endif
"     if !hasmapto("<Plug>UnCommentLines", "v")
" 	exe "vmap <buffer> <silent> ".g:atp_map_UnComment."	<Plug>UnCommentLines"
"     endif
endif

" MOVE AROUND COMMENTS: {{{1
if !hasmapto("<Plug>ParagraphNormalMotion")
    nmap <buffer> <silent> }	<Plug>ParagraphNormalMotionForward
    nmap <buffer> <silent> {	<Plug>ParagraphNormalMotionBackward
endif
nmap <buffer> <silent> v :call atplib#motion#StartVisualMode('v')<CR>
nmap <buffer> <silent> V :call atplib#motion#StartVisualMode('V')<CR>
nmap <buffer> <silent> <C-v> :call atplib#motion#StartVisualMode('cv')<CR>
if !hasmapto("<Plug>ParagraphVisualMotion")
    vmap <buffer> <silent> } 	<Plug>ParagraphVisualMotionForward
    vmap <buffer> <silent> { 	<Plug>ParagraphVisualMotionBackward
endif
omap <buffer> <silent> 	} :<C-U>exe "normal ".v:count1."}"<CR>
omap <buffer> <silent> 	{ :<C-U>exe "normal ".v:count1."{"<CR>

if !hasmapto(":SkipCommentForward<CR>", 'n')
    nmap <buffer> <silent> ]*	:SkipCommentForward<CR>
    nmap <buffer> <silent> ]%	:SkipCommentForward<CR>
    nmap <buffer> <silent> gc	:SkipCommentForward<CR>
endif
if !hasmapto(":SkipCommentForward<CR>", 'o')
    omap <buffer> <silent> ]*	:SkipCommentForward<CR>
    omap <buffer> <silent> ]%	:SkipCommentForward<CR>
    omap <buffer> <silent> gc	:SkipCommentForward<CR>
endif
if !hasmapto("<Plug>SkipCommentForward", 'v')
    vmap <buffer> <silent> ]*	<Plug>SkipCommentForward
    vmap <buffer> <silent> ]%	<Plug>SkipCommentForward
    vmap <buffer> <silent> gc	<Plug>SkipCommentForward
endif

if !hasmapto("<Plug>SkipCommentBackward<CR>", 'n')
    nmap <buffer> <silent> [*	:SkipCommentBackward<CR>
    nmap <buffer> <silent> [%	:SkipCommentBackward<CR>
    nmap <buffer> <silent> gC	:SkipCommentBackward<CR>
endif
if !hasmapto("<Plug>SkipCommentBackward<CR>", 'o')
    omap <buffer> <silent> [*	:SkipCommentBackward<CR>
    omap <buffer> <silent> [%	:SkipCommentBackward<CR>
    omap <buffer> <silent> gC	:SkipCommentBackward<CR>
endif
if !hasmapto("<Plug>SkipCommentBackward", 'v')
    vmap <buffer> <silent> [*	<Plug>SkipCommentBackward
    vmap <buffer> <silent> [%	<Plug>SkipCommentBackward
    vmap <buffer> <silent> gC	<Plug>SkipCommentBackward
endif

if !hasmapto(":NInput<CR>")
    execute "nmap <silent> <buffer> ".g:atp_map_forward_motion_leader."i	:NInput<CR>"
    execute "nmap <silent> <buffer> ".g:atp_map_forward_motion_leader."gf	:NInput<CR>"
endif

if !hasmapto(":PInput<CR>")
    execute "nmap <silent> <buffer> ".g:atp_map_backward_motion_leader."i	:PInput<CR>"
    execute "nmap <silent> <buffer> ".g:atp_map_backward_motion_leader."gf	:PInput<CR>"
endif

" MOTIONS: {{{1
" imap <buffer> <C-j> <Plug>TexSyntaxMotionForward
" imap <buffer> <C-k> <Plug>TexSyntaxMotionBackward
" nmap <buffer> <C-j> <Plug>TexSyntaxMotionForward
" nmap <buffer> <C-k> <Plug>TexSyntaxMotionBackward

if !hasmapto("<Plug>TexJMotionForward", 'i')
    imap <buffer> <C-j> <Plug>TexJMotionForward
endif
if !hasmapto("<Plug>TexJMotionForward", 'n')
    nmap <buffer> <C-j> <Plug>TexJMotionForward
endif
if !hasmapto("<Plug>TexJMotionBackward", 'i')
    imap <buffer> <C-k> <Plug>TexJMotionBackward
endif
if !hasmapto("<Plug>TexJMotionBackward", 'n')
    nmap <buffer> <C-k> <Plug>TexJMotionBackward
endif

" Repair: } and { 
if g:atp_map_forward_motion_leader == "}"
    noremap <silent> <buffer> }} }
endif
if g:atp_map_backward_motion_leader == "{"
    noremap <silent> <buffer> {{ {
endif
" Repair: > and >> (<, <<) operators:
if g:atp_map_forward_motion_leader == ">"
    nnoremap <buffer> <silent> >>  :<C-U>exe "normal! ".v:count1.">>"<CR>
    vnoremap <buffer> <silent> >>  :<C-U>exe "'<,'>normal! v".v:count1.">>"<CR>
endif
if g:atp_map_backward_motion_leader == "<"
    nnoremap <buffer> <silent> <<  :<C-U>exe "normal! ".v:count1."<<"<CR>
    vnoremap <buffer> <silent> <<  :<C-U>exe "'<,'>normal! v".v:count1."<<"<CR>
endif

if !hasmapto("<Plug>GotoNextSubSection", 'n')
    execute "nmap <silent> <buffer> ".g:atp_map_forward_motion_leader."S 	<Plug>GotoNextSubSection"
endif
if !hasmapto("<Plug>vGotoNextSubSection", 'v')
    execute "vmap <silent> <buffer> ".g:atp_map_forward_motion_leader."S	<Plug>vGotoNextSubSection"
endif
if !hasmapto("<Plug>GotoPreviousSubSection", 'n')
    execute "nmap <silent> <buffer> ".g:atp_map_backward_motion_leader."S 	<Plug>GotoPreviousSubSection"
endif
if !hasmapto("<Plug>vGotoPreviousSubSection", 'v')
    execute "vmap <silent> <buffer> ".g:atp_map_backward_motion_leader."S 	<Plug>vGotoPreviousSubSection"
endif
if !hasmapto("<Plug>GotoNextSection", 'n')
    execute "nmap <silent> <buffer> ".g:atp_map_forward_motion_leader."s 	<Plug>GotoNextSection"
endif
if !hasmapto("<Plug>vGotoNextSection", 'v')
    execute "vmap <silent> <buffer> ".g:atp_map_forward_motion_leader."s	<Plug>vGotoNextSection"
endif
if !hasmapto("<Plug>GotoPreviousSection", 'n')
    execute "nmap <silent> <buffer> ".g:atp_map_backward_motion_leader."s 	<Plug>GotoPreviousSection"
endif
if !hasmapto("<Plug>vGotoPreviousSection", 'v')
    execute "vmap <silent> <buffer> ".g:atp_map_backward_motion_leader."s 	<Plug>vGotoPreviousSection"
endif
if !( g:atp_map_forward_motion_leader == "]" && &l:diff )
    if !hasmapto("<Plug>GotoNextChapter", 'n')
	execute "nmap <silent> <buffer> ".g:atp_map_forward_motion_leader."c 	<Plug>GotoNextChapter"
    endif
    if !hasmapto("<Plug>vGotoNextChapter", 'v')
	execute "vmap <silent> <buffer> ".g:atp_map_forward_motion_leader."c 	<Plug>vGotoNextChapter"
    endif
endif
if !( g:atp_map_backward_motion_leader == "]" && &l:diff )
    if !hasmapto("<Plug>GotoPreviousChapter", 'n')
	execute "nmap <silent> <buffer> ".g:atp_map_backward_motion_leader."c 	<Plug>GotoPreviousChapter"
    endif
    if !hasmapto("<Plug>vGotoPreviousChapter", 'v')
	execute "vmap <silent> <buffer> ".g:atp_map_backward_motion_leader."c 	<Plug>vGotoPreviousChapter"
    endif
endif
if !hasmapto("<Plug>GotoNextPart", 'n')
    execute "nmap <silent> <buffer> ".g:atp_map_forward_motion_leader."p 	<Plug>GotoNextPart"
endif
if !hasmapto("<Plug>vGotoNextPart", 'v')
    execute "vmap <silent> <buffer> ".g:atp_map_forward_motion_leader."p 	<Plug>vGotoNextPart"
endif
if !hasmapto("<Plug>GotoPreviousPart", "n")
    execute "nmap <silent> <buffer> ".g:atp_map_backward_motion_leader."p 	<Plug>GotoPreviousPart"
endif
if !hasmapto("<Plug>vGotoPreviousPart", 'v')
    execute "vmap <silent> <buffer> ".g:atp_map_backward_motion_leader."p 	<Plug>vGotoPreviousPart"
endif

if !hasmapto("<Plug>GotoNextEnvironment", "n")
    execute "nmap <silent> <buffer> ".g:atp_map_forward_motion_leader."e	<Plug>GotoNextEnvironment"
endif
if !hasmapto("<Plug>JumptoNextEnvironment", "n")
    execute "nmap <silent> <buffer> ".g:atp_map_forward_motion_leader."E	<Plug>JumptoNextEnvironment"
endif
if !hasmapto("<Plug>GotoPreviousEnvironment", "n")
    execute "nmap <silent> <buffer> ".g:atp_map_backward_motion_leader."e	<Plug>GotoPreviousEnvironment"
endif
if !hasmapto("<Plug>JumptoPreviousEnvironment", "n")
    execute "nmap <silent> <buffer> ".g:atp_map_backward_motion_leader."E 	<Plug>JumptoPreviousEnvironment"
endif
if !hasmapto("<Plug>GotoNextMath", "n")
    execute "nmap <silent> <buffer> ".g:atp_map_forward_motion_leader."m	<Plug>GotoNextMath"
endif
if !hasmapto("<Plug>GotoPreviousMath", "n")
    execute "nmap <silent> <buffer> ".g:atp_map_backward_motion_leader."m	<Plug>GotoPreviousMath"
endif
if !hasmapto("<Plug>GotoNextDisplayedMath", "n")
    execute "nmap <silent> <buffer> ".g:atp_map_forward_motion_leader."M	<Plug>GotoNextDisplayedMath"
endif
if !hasmapto("<Plug>GotoPreviousDisplayedMath", "n")
    execute "nmap <silent> <buffer> ".g:atp_map_backward_motion_leader."M	<Plug>GotoPreviousDisplayedMath"
endif

" GOTO FILE MAP: {{{1
if has("path_extra") && !hasmapto(" GotoFile(", 'n')
	nnoremap <buffer> <silent> gf		:call atplib#motion#GotoFile("", "")<CR>
endif

if !g:atp_tab_map
    "Default Completion Maps:
    inoremap <silent> <buffer> <C-x><C-o> <C-R>=atplib#complete#TabCompletion(1)<CR>
    inoremap <silent> <buffer> <C-x>o <C-R>=atplib#complete#TabCompletion(0)<CR>
else 
    "Non Default Completion Maps:
    if !hasmapto("<C-R>=atplib#complete#TabCompletion(1)<CR>", 'i')
	imap <silent> <buffer> <Tab> 		<C-R>=atplib#complete#TabCompletion(1)<CR>
    endif
    if !hasmapto("<C-R>=atplib#complete#TabCompletion(0)<CR>", 'i')
	imap <silent> <buffer> <S-Tab> 		<C-R>=atplib#complete#TabCompletion(0)<CR>
    endif
endif
if !hasmapto(":Wrap { } begin<cr>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_bracket_leader."{ 	:Wrap { } begin<CR>"
endif

" WRAPERS: {{{1
" OPERATOR FONT MAPS: {{{2
function! ATP_LastWrap(type)
    if a:type == "block" | return | endif
    let marks = ["'[", "']"]
    call atplib#various#RedoLastWrapSelection(marks)
endfunction
exe "nmap <buffer> ".g:atp_vmap_text_font_leader."w :set opfunc=ATP_LastWrap<CR>g@"
function! ATP_WrapBold(type)
    if a:type == "block" | return | endif
    call atplib#various#InteligentWrapSelection(['\textbf{'], ['\mathbf{'], 'end', 0, ["'[", "']"])
endfunction
exe "nmap <buffer> ".g:atp_vmap_text_font_leader."bf :set opfunc=ATP_WrapBold<CR>g@"
function! ATP_WrapBB(type)
    if a:type == "block" | return | endif
    call atplib#various#InteligentWrapSelection(['\textbf{'], ['\mathbb{'], 'end', 0, ["'[", "']"])
endfunction
exe "nmap <buffer> ".g:atp_vmap_text_font_leader."bb :set opfunc=ATP_WrapBB<CR>g@"
function! ATP_WrapItalic(type)
    if a:type == "block" | return | endif
    call atplib#various#InteligentWrapSelection(['\textit{'], ['\mathit{'], 'end', 0, ["'[", "']"])
endfunction
exe "nmap <buffer> ".g:atp_vmap_text_font_leader."it :set opfunc=ATP_WrapItalic<CR>g@"
function! ATP_WrapEmph(type)
    if a:type == "block" | return | endif
    call atplib#various#InteligentWrapSelection(['\emph{'], ['\mathit{'], 'end', 0, ["'[", "']"])
endfunction
exe "nmap <buffer> ".g:atp_vmap_text_font_leader."em :set opfunc=ATP_WrapEmph<CR>g@"
function! ATP_WrapSF(type)
    if a:type == "block" | return | endif
    call atplib#various#InteligentWrapSelection(['\textsf{'], ['\mathsf{'], 'end', 0, ["'[", "']"])
endfunction
exe "nmap <buffer> ".g:atp_vmap_text_font_leader."sf :set opfunc=ATP_WrapSF<CR>g@"
function! ATP_WrapTT(type)
    if a:type == "block" | return | endif
    call atplib#various#InteligentWrapSelection(['\texttt{'], ['\mathtt{'], 'end', 0, ["'[", "']"])
endfunction
exe "nmap <buffer> ".g:atp_vmap_text_font_leader."tt :set opfunc=ATP_WrapTT<CR>g@"
function! ATP_WrapSL(type)
    if a:type == "block" | return | endif
    call atplib#various#WrapSelection('\textsl{', '}', 'end', 0, ["'[", "']"])
endfunction
exe "nmap <buffer> ".g:atp_vmap_text_font_leader."sl :set opfunc=ATP_WrapSL<CR>g@"
function! ATP_WrapSC(type)
    if a:type == "block" | return | endif
    call atplib#various#WrapSelection('\textsc{', '}', 'end', 0, ["'[", "']"])
endfunction
exe "nmap <buffer> ".g:atp_vmap_text_font_leader."sc :set opfunc=ATP_WrapSC<CR>g@"
function! ATP_WrapUP(type)
    if a:type == "block" | return | endif
    call atplib#various#WrapSelection('\textup{', '}', 'end', 0, ["'[", "']"])
endfunction
exe "nmap <buffer> ".g:atp_vmap_text_font_leader."up :set opfunc=ATP_WrapUP<CR>g@"
function! ATP_WrapMD(type)
    if a:type == "block" | return | endif
    call atplib#various#WrapSelection('\textmd{', '}', 'end', 0, ["'[", "']"])
endfunction
" g:atp_vmap_text_font_leader is used instead of g:atp_imap_over_leader = "`"
" which interferes with marks.
exe "nmap <buffer> ".g:atp_vmap_text_font_leader."md :set opfunc=ATP_WrapMD<CR>g@"
function! ATP_WrapUnderline(type)
    if a:type == "block" | return | endif
    call atplib#various#WrapSelection('\underline{', '}', 'end', 0, ["'[", "']"])
endfunction
" g:atp_vmap_text_font_leader is used instead of g:atp_imap_over_leader = "`"
" which interferes with marks.
exe "nmap <buffer> ".g:atp_vmap_text_font_leader."un :set opfunc=ATP_WrapUnderline<CR>g@"
function! ATP_WrapOverline(type)
    if a:type == "block" | return | endif
    call atplib#various#WrapSelection('\overline{', '}', 'end', 0, ["'[", "']"])
endfunction
exe "nmap <buffer> ".g:atp_vmap_text_font_leader."ov :set opfunc=ATP_WrapOverline<CR>g@"
function! ATP_WrapCal(type)
    if a:type == "block" | return | endif
    if atplib#IsInMath()
	call atplib#various#WrapSelection('\mathcal{', '}', 'end', 0, ["'[", "']"])
    endif
endfunction
exe "nmap <buffer> ".g:atp_vmap_text_font_leader."cal :set opfunc=ATP_WrapCal<CR>g@"

" FONTS: {{{2
if !hasmapto(":Wrap {".s:backslash."usefont{".g:atp_font_encoding."}{}{}{}\\selectfont", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_text_font_leader."f	:Wrap {".s:backslash."usefont{".g:atp_font_encoding."}{}{}{}\\selectfont\\  } ".(len(g:atp_font_encoding)+11)."<CR>"
endif
if !hasmapto(":Wrap ".s:backslash."mbox{", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_text_font_leader."mb	:Wrap ".s:backslash."mbox{ } begin<CR>"
endif

if !hasmapto(":<C-U>IWrap ['".s:backslash."textrm{'],['".s:backslash."text{']<CR>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_text_font_leader."te	:<C-U>IWrap ['".s:backslash."textrm{'],['".s:backslash."text{']<CR>"
endif
if !hasmapto(":<C-U>IWrap ['".s:backslash."textrm{'],['".s:backslash."mathrm{']<CR>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_text_font_leader."rm	:<C-U>IWrap ['".s:backslash."textrm{'],['".s:backslash."mathrm{']<CR>"
endif
if !hasmapto(":<C-U>IWrap ['".s:backslash."emph{'],['".s:backslash."mathit{']<CR>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_text_font_leader."em	:<C-U>IWrap ['".s:backslash."emph{'],['".s:backslash."mathit{']<CR>"
endif
"   Suggested Maps:
"     execute "vnoremap <silent> <buffer> ".g:atp_vmap_text_font_leader."tx	:<C-U>IWrap [''],['".s:backslash."text{']<CR>"
"     execute "vnoremap <silent> <buffer> ".g:atp_vmap_text_font_leader."in	:<C-U>IWrap [''],['".s:backslash."intertext{']<CR>"
if !hasmapto(":<C-U>IWrap ['".s:backslash."textit{'],['".s:backslash."mathit{']<CR>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_text_font_leader."it	:<C-U>IWrap ['".s:backslash."textit{'],['".s:backslash."mathit{']<CR>"
endif
if !hasmapto(":<C-U>IWrap ['".s:backslash."textsf{'],['".s:backslash."mathsf{']<CR>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_text_font_leader."sf	:<C-U>IWrap ['".s:backslash."textsf{'],['".s:backslash."mathsf{']<CR>"
endif
if !hasmapto(":<C-U>IWrap ['".s:backslash."texttt{'],['".s:backslash."mathtt{']<CR>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_text_font_leader."tt	:<C-U>IWrap ['".s:backslash."texttt{'],['".s:backslash."mathtt{']<CR>"
endif
if !hasmapto(":<C-U>IWrap ['".s:backslash."textbf{'],['".s:backslash."mathbf{']<CR>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_text_font_leader."bf	:<C-U>IWrap ['".s:backslash."textbf{'],['".s:backslash."mathbf{']<CR>"
endif
if !hasmapto(":<C-U>IWrap ['".s:backslash."textbf{'],['".s:backslash."mathbb{']<CR>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_text_font_leader."bb	:<C-U>IWrap ['".s:backslash."textbf{'],['".s:backslash."mathbb{']<CR>"
endif
if !hasmapto(":<C-U>Wrap ".s:backslash."textsl{<CR>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_text_font_leader."sl	:<C-U>Wrap ".s:backslash."textsl{<CR>"
endif
if !hasmapto(":<C-U>Wrap ".s:backslash."textsc{<CR>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_text_font_leader."sc	:<C-U>Wrap ".s:backslash."textsc{<CR>"
endif
if !hasmapto(":<C-U>Wrap ".s:backslash."textup{<CR>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_text_font_leader."up	:<C-U>Wrap ".s:backslash."textup{<CR>"
endif
if !hasmapto(":<C-U>Wrap ".s:backslash."textmd{<CR>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_text_font_leader."md	:<C-U>Wrap ".s:backslash."textmd{<CR>"
endif
if !hasmapto(":<C-U>Wrap ".s:backslash."underline{<CR>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_text_font_leader."un	:<C-U>Wrap ".s:backslash."underline{<CR>"
endif
if !hasmapto(":<C-U>Wrap ".s:backslash."overline{<CR>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_text_font_leader."ov	:<C-U>Wrap ".s:backslash."overline{<CR>"
endif
if !hasmapto(":<C-U>IWrap ['".s:backslash."textnormal{'],['".s:backslash."mathnormal{']<CR>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_text_font_leader."no	:<C-U>IWrap ['".s:backslash."textnormal{'],['".s:backslash."mathnormal{']<CR>"
endif
if !hasmapto(":<C-U>IWrap [''],['".s:backslash."mathcal{']<CR>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_text_font_leader."cal	:<C-U>IWrap [''],['".s:backslash."mathcal{']<CR>"
endif
if !hasmapto("atplib#various#RedoLastWrapSelection", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_text_font_leader."w	<Esc>:<C-U>:call atplib#various#RedoLastWrapSelection([\"'<\", \"'>\"])<CR>"
endif

" ENVIRONMENTS: {{{2
if !hasmapto(":Wrap ".s:backslash."begin{center} ".s:backslash."end{center} 0 1<CR>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_environment_leader."C   :Wrap ".s:backslash."begin{center} ".s:backslash."end{center} 0 1<CR>"
endif
if !hasmapto(":Wrap ".s:backslash."begin{flushright} ".s:backslash."end{flushright} 0 1<CR>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_environment_leader."R   :Wrap ".s:backslash."begin{flushright} ".s:backslash."end{flushright} 0 1<CR>"
endif
if !hasmapto(":Wrap ".s:backslash."begin{flushleft} ".s:backslash."end{flushleft} 0 1<CR>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_environment_leader."L   :Wrap ".s:backslash."begin{flushleft} ".s:backslash."end{flushleft} 0 1<CR>"
endif
if !hasmapto(":Wrap ".s:backslash."begin{equation=b:atp_StarMathEnvDefault<CR>} ".s:backslash."end{equation=b:atp_StarMathEnvDefault<CR>} 0 1<CR>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_environment_leader."E   :Wrap ".s:backslash."begin{equation=b:atp_StarMathEnvDefault<CR>} ".s:backslash."end{equation=b:atp_StarMathEnvDefault<CR>} 0 1<CR>"
endif
if !hasmapto(":Wrap ".s:backslash."begin{align=b:atp_StarMathEnvDefault<CR>} ".s:backslash."end{align=b:atp_StarMathEnvDefault<CR>} 0 1<CR>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_environment_leader."A   :Wrap ".s:backslash."begin{align=b:atp_StarMathEnvDefault<CR>} ".s:backslash."end{align=b:atp_StarMathEnvDefault<CR>} 0 1<CR>"
endif

" MATH MODES: {{{2
if !hasmapto(':<C-U>Wrap '.s:backslash.'( '.s:backslash.')<CR>', 'v')
    exe "vmap <silent> <buffer> m				:<C-U>Wrap ".s:backslash."( ".s:backslash.")<CR>"
endif
function! ATP_WrapVMath(type)
    if a:type == "block" | return | endif
    call atplib#various#WrapSelection('\(', '\)', 'begin', 0, ["'[", "']"])
endfunction
exe "nmap <buffer> ".g:atp_vmap_bracket_leader."m :set opfunc=ATP_WrapVMath<CR>g@"
if !hasmapto(':<C-U>Wrap '.s:backslash.'[ '.s:backslash.']<CR>', 'v')
    exe "vmap <silent> <buffer> M				:<C-U>Wrap ".s:backslash."[ ".s:backslash."]<CR>"
endif
function! ATP_WrapWMath(type)
    if a:type == "block" | return | endif
    call atplib#various#WrapSelection('\[', '\]', 'begin', 0, ["'[", "']"])
endfunction
exe "nmap <buffer> ".g:atp_vmap_bracket_leader."M :set opfunc=ATP_WrapWMath<CR>g@"

" BRACKETS: {{{2
if !hasmapto(":Wrap ( ) begin<cr>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_bracket_leader."( 	:Wrap ( ) begin<CR>"
endif
function! ATP_WrapKet_1_begin(type)
    if a:type == "block" | return | endif
    call atplib#various#WrapSelection('(', ')', 'begin', 0, ["'[", "']"])
endfunction
exe "nmap <buffer> ".g:atp_vmap_bracket_leader."( :set opfunc=ATP_WrapKet_1_begin<CR>g@"
if !hasmapto(":Wrap ( ) end<cr>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_bracket_leader.") 	:Wrap ( ) end<CR>"
endif
function! ATP_WrapKet_1_end(type)
    if a:type == "block" | return | endif
    call atplib#various#WrapSelection('(', ')', 'end', 0, ["'[", "']"])
endfunction
exe "nmap <buffer> ".g:atp_vmap_bracket_leader.") :set opfunc=ATP_WrapKet_1_end<CR>g@"
if !hasmapto(":Wrap [ ] begin<cr>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_bracket_leader."[ 	:Wrap [ ] begin<CR>"
endif
function! ATP_WrapKet_2_begin(type)
    if a:type == "block" | return | endif
    call atplib#various#WrapSelection('[', ']', 'begin', 0, ["'[", "']"])
endfunction
exe "nmap <buffer> ".g:atp_vmap_bracket_leader."[ :set opfunc=ATP_WrapKet_2_begin<CR>g@"
if !hasmapto(":Wrap [ ] end<cr>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_bracket_leader."] 	:Wrap [ ] end<CR>"
endif
function! ATP_WrapKet_2_end(type)
    if a:type == "block" | return | endif
    call atplib#various#WrapSelection('[', ']', 'end', 0, ["'[", "']"])
endfunction
exe "nmap <buffer> ".g:atp_vmap_bracket_leader."] :set opfunc=ATP_WrapKet_2_end<CR>g@"
if !hasmapto(":Wrap ".s:backslash."{ ".s:backslash."} begin<cr>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_bracket_leader.s:backslash."{	:Wrap ".s:backslash."{ ".s:backslash."} begin<CR>"
endif
function! ATP_WrapKet_3_begin(type)
    if a:type == "block" | return | endif
    call atplib#various#WrapSelection('\{', '\}', 'begin', 0, ["'[", "']"])
endfunction
exe "nmap <buffer> ".g:atp_vmap_bracket_leader.s:backslash."{ :set opfunc=ATP_WrapKet_3_begin<CR>g@"
if !hasmapto(":Wrap ".s:backslash."} ".s:backslash."} end<cr>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_bracket_leader.s:backslash."}	:Wrap ".s:backslash."{ ".s:backslash."} end<CR>"
endif
function! ATP_WrapKet_3_end(type)
    if a:type == "block" | return | endif
    call atplib#various#WrapSelection('\{', '\}', 'end', 0, ["'[", "']"])
endfunction
exe "nmap <buffer> ".g:atp_vmap_bracket_leader.s:backslash."} :set opfunc=ATP_WrapKet_3_end<CR>g@"
" This is defined before:
" if !hasmapto(":Wrap { } begin<cr>", 'v')
"     execute "vnoremap <silent> <buffer> ".g:atp_vmap_bracket_leader."{ 	:Wrap { } begin<CR>"
" endif
function! ATP_WrapKet_4_begin(type)
    if a:type == "block" | return | endif
    call atplib#various#WrapSelection('{', '}', 'begin', 0, ["'[", "']"])
endfunction
exe "nmap <buffer> ".g:atp_vmap_bracket_leader."{ :set opfunc=ATP_WrapKet_4_begin<CR>g@"
if !hasmapto(":Wrap { } end<cr>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_bracket_leader."}	:Wrap { } end<CR>"
endif
function! ATP_WrapKet_4_end(type)
    if a:type == "block" | return | endif
    call atplib#various#WrapSelection('{', '}', 'end', 0, ["'[", "']"])
endfunction
exe "nmap <buffer> ".g:atp_vmap_bracket_leader."} :set opfunc=ATP_WrapKet_4_end<CR>g@"
if !hasmapto(":Wrap < > begin<cr>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_bracket_leader."< 	:Wrap < > begin<CR>"
endif
function! ATP_WrapKet_5_begin(type)
    if a:type == "block" | return | endif
    call atplib#various#WrapSelection('<', '>', 'begin', 0, ["'[", "']"])
endfunction
exe "nmap <buffer> ".g:atp_vmap_bracket_leader."< :set opfunc=ATP_WrapKet_5_begin<CR>g@"
if !hasmapto(":Wrap < > end<cr>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_bracket_leader."> 	:Wrap < > end<CR>"
endif
function! ATP_WrapKet_5_end(type)
    if a:type == "block" | return | endif
    call atplib#various#WrapSelection('<', '>', 'end', 0, ["'[", "']"])
endfunction
exe "nmap <buffer> ".g:atp_vmap_bracket_leader."> :set opfunc=ATP_WrapKet_5_end<CR>g@"
if !hasmapto(":Wrap ".s:backslash."left( ".s:backslash."right) end<CR>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_big_bracket_leader.")	:Wrap ".s:backslash."left( ".s:backslash."right) end<CR>"
endif
function! ATP_WrapBigKet_1_end(type)
    if a:type == "block" | return | endif
    call atplib#various#WrapSelection('\left(', '\right)', 'end', 0, ["'[", "']"])
endfunction
exe "nmap <buffer> ".g:atp_vmap_big_bracket_leader.") :set opfunc=ATP_WrapBigKet_1_end<CR>g@"
if !hasmapto(":Wrap ".s:backslash."left[ ".s:backslash."right] end<cr>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_big_bracket_leader."]	:Wrap ".s:backslash."left[ ".s:backslash."right] end<cr>"
endif
function! ATP_WrapBigKet_2_end(type)
    if a:type == "block" | return | endif
    call atplib#various#WrapSelection('\left[', '\right]', 'end', 0, ["'[", "']"])
endfunction
exe "nmap <buffer> ".g:atp_vmap_big_bracket_leader."] :set opfunc=ATP_WrapBigKet_2_end<CR>g@"
if !hasmapto(":Wrap ".s:backslash."left".s:backslash."{ ".s:backslash."right".s:backslash."} end<CR>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_big_bracket_leader.s:backslash."}	:Wrap ".s:backslash."left".s:backslash."{ ".s:backslash."right".s:backslash."} end<CR>"
endif
function! ATP_WrapBigKet_3_end(type)
    if a:type == "block" | return | endif
    call atplib#various#WrapSelection('\left\{', '\right\}', 'end', 0, ["'[", "']"])
endfunction
exe "nmap <buffer> ".g:atp_vmap_big_bracket_leader.s:backslash."} :set opfunc=ATP_WrapBigKet_3_end<CR>g@"
" for compatibility:
if !hasmapto(":Wrap ".s:backslash."left( ".s:backslash."right) begin<CR>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_big_bracket_leader."(	:Wrap ".s:backslash."left( ".s:backslash."right) begin<CR>"
endif
function! ATP_WrapBigKet_1_begin(type)
    if a:type == "block" | return | endif
    call atplib#various#WrapSelection('\left(', '\right)', 'begin', 0, ["'[", "']"])
endfunction
exe "nmap <buffer> ".g:atp_vmap_big_bracket_leader."( :set opfunc=ATP_WrapBigKet_1_begin<CR>g@"
if !hasmapto(":Wrap ".s:backslash."left[ ".s:backslash."right] begin<CR>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_big_bracket_leader."[	:Wrap ".s:backslash."left[ ".s:backslash."right] begin<CR>"
endif
function! ATP_WrapBigKet_2_begin(type)
    if a:type == "block" | return | endif
    call atplib#various#WrapSelection('\left[', '\right]', 'begin', 0, ["'[", "']"])
endfunction
exe "nmap <buffer> ".g:atp_vmap_big_bracket_leader."[ :set opfunc=ATP_WrapBigKet_2_begin<CR>g@"
if !hasmapto(":Wrap ".s:backslash."left".s:backslash."{ ".s:backslash."right".s:backslash."} begin<CR>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_big_bracket_leader.s:backslash."{	:Wrap ".s:backslash."left".s:backslash."{ ".s:backslash."right".s:backslash."} begin<CR>"
endif
function! ATP_WrapBigKet_3_begin(type)
    if a:type == "block" | return | endif
    call atplib#various#WrapSelection('\left\{', '\right\}', 'begin', 0, ["'[", "']"])
endfunction
exe "nmap <buffer> ".g:atp_vmap_big_bracket_leader.s:backslash."{ :set opfunc=ATP_WrapBigKet_3_begin<CR>g@"
if !hasmapto(":Wrap ".s:backslash."left".s:backslash."{ ".s:backslash."right".s:backslash."} end<CR>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_big_bracket_leader."}	:Wrap ".s:backslash."left".s:backslash."{ ".s:backslash."right".s:backslash."} end<CR>"
endif

" ACCENTS: {{{2
if !hasmapto(":<C-U>IWrap ['".s:backslash."''{'],['".s:backslash."acute{']<CR>", "v")
    execute "vnoremap <silent> <buffer> ".g:atp_imap_over_leader."' 		:<C-U>IWrap ['".s:backslash."''{'],['".s:backslash."acute{']<CR>"
endif
if !hasmapto(":<C-U>Wrap ".s:backslash."\"{ } end<CR>", "v")
    execute "vnoremap <silent> <buffer> ".g:atp_imap_over_leader."\"		:<C-U>Wrap ".s:backslash."\"{ } end<CR>"
endif
if !hasmapto(":<C-U>Wrap ".s:backslash."^{ } end<CR>", "v")
    execute "vnoremap <silent> <buffer> ".g:atp_imap_over_leader."^		:<C-U>Wrap ".s:backslash."^{ } end<CR>"
endif
if !hasmapto(":<C-U>IWrap ['".s:backslash."v{'],['".s:backslash."check{']<CR>", "v")
    execute "vnoremap <silent> <buffer> ".g:atp_imap_over_leader."v 		:<C-U>IWrap ['".s:backslash."v{'],['".s:backslash."check{']<CR>"
endif
if !hasmapto(":<C-U>IWrap ['".s:backslash."`{'],['".s:backslash."grave{']<CR>", "v")
    execute "vnoremap <silent> <buffer> ".g:atp_imap_over_leader."` 		:<C-U>IWrap ['".s:backslash."`{'],['".s:backslash."grave{']<CR>"
endif
if !hasmapto(":<C-U>Wrap ".s:backslash."b{ } end<CR>", "v")
    execute "vnoremap <silent> <buffer> ".g:atp_imap_over_leader."b		:<C-U>Wrap ".s:backslash."b{ } end<CR>"
endif
if !hasmapto(":<C-U>Wrap ".s:backslash."d{ } end<CR>", "v")
    execute "vnoremap <silent> <buffer> ".g:atp_imap_over_leader."d		:<C-U>Wrap ".s:backslash."d{ } end<CR>"
endif
if !hasmapto(":<C-U>Wrap ".s:backslash."H{ } end<CR>", "v")
    execute "vnoremap <silent> <buffer> ".g:atp_imap_over_leader."H		:<C-U>Wrap ".s:backslash."H{ } end<CR>"
endif
if !hasmapto(":<C-U>Wrap ".s:backslash."~{ } end<CR>", "v")
    execute "vnoremap <silent> <buffer> ".g:atp_imap_over_leader."~		:<C-U>Wrap ".s:backslash."~{ } end<CR>"
endif
if !hasmapto(":<C-U>IWrap ['".s:backslash.".{'],['".s:backslash."dot{']<CR>", "v")
    execute "vnoremap <silent> <buffer> ".g:atp_imap_over_leader.". 		:<C-U>IWrap ['".s:backslash.".{'],['".s:backslash."dot{']<CR>"
endif
if !hasmapto(":<C-U>Wrap ".s:backslash."c{ } end<CR>", "v")
    execute "vnoremap <silent> <buffer> ".g:atp_imap_over_leader."c		:<C-U>Wrap ".s:backslash."c{ } end<CR>"
endif
if !hasmapto(":<C-U>Wrap ".s:backslash."t{ } end<CR>", "v")
    execute "vnoremap <silent> <buffer> ".g:atp_imap_over_leader."t		:<C-U>Wrap ".s:backslash."t{ } end<CR>"
endif
execute "vnoremap <silent> <buffer> <expr>".g:atp_imap_over_leader."~		':<C-U>Wrap ".s:backslash."'.(g:atp_imap_wide ? \"wide\" : \"\").'tilde{ } end<CR>'"

" TEX ALIGN: {{{1
if !hasmapto(":TexAlign<CR>", 'n')
    nmap <silent> <buffer> <Localleader>a	<Plug>TexAlign
endif

" PARAGRAPH SELECTION: {{{1
if !hasmapto("<Plug>ATP_SelectCurrentParagraphInner", 'v')
    vmap <silent> <buffer> ip 	<Plug>ATP_SelectCurrentParagraphInner
endif
if !hasmapto("<Plug>ATP_SelectCurrentParagraphOuter", 'v')
    vmap <silent> <buffer> ap 	<Plug>ATP_SelectCurrentParagraphOuter
endif
if !hasmapto(" vip<CR>", "o")
    omap <silent> <buffer>  ip	:normal vip<CR>
endif
if !hasmapto(" vap<CR>", "o")
    omap <silent> <buffer>  ap	:normal vap<CR>
endif

" FORMATING: {{{1
if !hasmapto("m`vipgq``", "n")
    nmap <silent> <buffer> gw		m`vipgq``
endif

" INDENT BLOCK: {{{1
nnoremap <buffer> g>	:<C-U>call feedkeys("m`vip".(v:count1 <= 1 ? "" : v:count1).">``", 't')<CR>
nnoremap <buffer> g<	:<C-U>call feedkeys("m`vip".(v:count1 <= 1 ? "" : v:count1)."<``", 't')<CR>

" SELECT SYNTAX: {{{1
if !hasmapto("<Plug>SelectOuterSyntax", "v")
    vmap <buffer> <silent> aS		<Plug>SelectOuterSyntax
endif
if !hasmapto("<Plug>SelectInnerSyntax", "v")
    vmap <buffer> <silent> iS		<Plug>SelectInnerSyntax
endif

" ENVIRONMENT MOVES: {{{1
" From vim.vim plugin (by Bram Mooleaner)
" Move around functions.
exe "nnoremap <silent> <buffer> <Plug>BegPrevEnvironment m':call search('".s:bbackslash."begin".s:backslash."s*{".s:bbackslash."|".s:backslash.s:bbackslash."@<!".s:backslash.s:bbackslash."[".s:bbackslash."|".s:backslash.s:bbackslash."@<!".s:backslash."$".s:backslash."$', 'bW')<CR>"
if !hasmapto("<Plug>BegPrevEnvironment", "n")
    nmap <silent> <buffer> [[ <Plug>BegPrevEnvironment
endif
exe "vnoremap <silent> <buffer> <Plug>vBegPrevEnvironment m':<C-U>exe \"normal! gv\"<Bar>call search('".s:bbackslash."begin".s:backslash."s*{".s:bbackslash."|".s:backslash.s:bbackslash."@<!".s:backslash.s:bbackslash."[".s:bbackslash."|".s:backslash.s:bbackslash."@<!".s:backslash."$".s:backslash."$', 'bW')<CR>"
if !hasmapto("<Plug>vBegPrevEnvironment", "v")
    vmap <silent> <buffer> [[ <Plug>vBegPrevEnvironment
endif
exe "nnoremap <silent> <buffer> <Plug>BegNextEnvironment m':call search('".s:bbackslash."begin".s:backslash."s*{".s:bbackslash."|".s:backslash.s:bbackslash."@<!".s:backslash.s:bbackslash."[".s:bbackslash."|".s:backslash.s:bbackslash."@<!".s:backslash."$".s:backslash."$', 'W')<CR>"
if !hasmapto("<Plug>BegNextEnvironment", "n")
    nmap <silent> <buffer> ]] <Plug>BegNextEnvironment
endif
exe "vnoremap <silent> <buffer> <Plug>vBegNextEnvironment m':<C-U>exe \"normal! gv\"<Bar>call search('".s:bbackslash."begin".s:backslash."s*{".s:bbackslash."|".s:backslash.s:bbackslash."@<!".s:backslash.s:bbackslash."[".s:bbackslash."|".s:backslash.s:bbackslash."@<!".s:backslash."$".s:backslash."$', 'W')<CR>"
if !hasmapto("<Plug>vBegNextEnvironment", "v")
    vmap <silent> <buffer> ]] <Plug>vBegNextEnvironment
endif
exe "nnoremap <silent> <buffer> <Plug>EndPrevEnvironment m':call search('".s:bbackslash."end".s:backslash."s*{".s:bbackslash."|".s:backslash.s:bbackslash."@<!".s:backslash.s:bbackslash."]".s:bbackslash."|".s:backslash.s:bbackslash."@<!".s:backslash."$".s:backslash."$', 'bW')<CR>"
if !hasmapto("<Plug>EndPrevEnvironment", "n")
    nmap <silent> <buffer> [] <Plug>EndPrevEnvironment
endif
exe "vnoremap <silent> <buffer> <Plug>vEndPrevEnvironment m':<C-U>exe \"normal! gv\"<Bar>call search('".s:bbackslash."end".s:backslash."s*{".s:bbackslash."|".s:backslash.s:bbackslash."@<!".s:backslash.s:bbackslash."]".s:bbackslash."|".s:backslash.s:bbackslash."@<!".s:backslash."$".s:backslash."$', 'bW')<CR>"
if !hasmapto("<Plug>vEndPrevEnvironment", "v")
    vmap <silent> <buffer> [] <Plug>vEndPrevEnvironment
endif
exe "nnoremap <silent> <buffer> <Plug>EndNextEnvironment m':call search('".s:bbackslash."end".s:backslash."s*{".s:bbackslash."|".s:backslash.s:bbackslash."@<!".s:backslash.s:bbackslash."]".s:bbackslash."|".s:backslash.s:bbackslash."@<!".s:backslash."$".s:backslash."$', 'W')<CR>"
if !hasmapto("<Plug>EndNextEnvironment", "n")
    nmap <silent> <buffer> ][ <Plug>EndNextEnvironment
endif
exe "vnoremap <silent> <buffer> <Plug>vEndNextEnvironment m':<C-U>exe \"normal! gv\"<Bar>call search('".s:bbackslash."end".s:backslash."s*{".s:bbackslash."|".s:backslash.s:bbackslash."@<!".s:backslash.s:bbackslash."]".s:bbackslash."|".s:backslash.s:bbackslash."@<!".s:backslash."$".s:backslash."$', 'W')<CR>"
if !hasmapto("<Plug>vEndNextEnvironment", "v")
    vmap <silent> <buffer> ][ <Plug>vEndNextEnvironment
endif

" SELECT COMMENT: {{{1
if !hasmapto("v<Plug>vSelectComment", "n")
    exe "nmap <silent> <buffer> ".g:atp_MapSelectComment." v<Plug>vSelectComment"
endif
if !hasmapto(g:atp_MapSelectComment, "o")
    exe "omap <silent> <buffer>".g:atp_MapSelectComment." :normal ".g:atp_MapSelectComment."<CR>"
endif
" SELECT FRAME: (beamer) {{{1
" This is done by a function, because it has to be run through an autocommand
" otherwise atplib#search#DocumentClass is not working.
function! <SID>BeamerOptions()
    if atplib#search#DocumentClass(b:atp_MainFile) == "beamer"
	
	" _f
	if !exists("g:atp_MapSelectFrame")
	    let g:atp_MapSelectFrame = "=f"
	endif
	if !hasmapto("v<Plug>vSelectFrameEnvironment", "n")
	    exe "nmap <silent> <buffer> ".g:atp_MapSelectFrame." <Plug>SelectFrameEnvironment"
" 	    exe "vmap <silent> <buffer> ".g:atp_MapSelectFrame." <Plug>vSelectFrameEnvironment"
	endif

	" >f, <f
	exe "nmap <buffer> <silent> <expr> ".g:atp_map_forward_motion_leader."f ':<C-U>'.v:count1.'F frame<CR>'"
	exe "nmap <buffer> <silent> <expr> ".g:atp_map_backward_motion_leader."f ':<C-U>'.v:count1.'B frame<CR>'"

	" >F, <F
	exe "nmap <buffer> <silent> ".g:atp_map_forward_motion_leader."F <Plug>NextFrame"
	exe "nmap <buffer> <silent> ".g:atp_map_backward_motion_leader."F <Plug>PreviousFrame"
    endif
endfunction
au BufEnter *.tex 	call <SID>BeamerOptions()

" NORMAL MODE MAPS: (most of them) {{{1

" Enabling this requires uncommenting augroup ATP_Cmdwin in options.vim
" exe "nnoremap  <silent> <buffer> <Plug>QForwardSearch 	q".s:backslash.":call ATP_CmdwinToggleSpace(1)<CR>i"
" if !hasmapto("<Plug>QForwardSearch", "n")
" "     if mapcheck('Q/', 'n') == ""
" 	nmap <silent> <buffer> Q/			<Plug>QForwardSearch
" "     endif
" endif
" exe "nmap <silent> <buffer> <Plug>QBackwardSearch	q?:call ATP_CmdwinToggleSpace(1)<CR>"
" if !hasmapto("<Plug>QBackwardSearch", "n")
" "     if mapcheck('Q?', 'n') == "" && !hasmapto("<Plug>QBackwardSearch", "n")
" 	nmap <silent> <buffer> Q?			<Plug>QBackwardSearch
" "     endif
" endif

if mapcheck('<LocalLeader>s$') == "" && !hasmapto("<Plug>ToggleStar", "n")
    nmap  <silent> <buffer> <LocalLeader>s		<Plug>ToggleStar
elseif !hasmapto("<Plug>ToggleStar", "n") && g:atp_debugMapFile && !g:atp_reload_functions
    echoerr "[ATP:] there will be no nmap to <Plug>ToggleStar"
endif

if !hasmapto("<Plug>TogglesilentMode", "n")
    nmap  <silent> <buffer> <LocalLeader><Localleader>s	<Plug>TogglesilentMode
endif
if !hasmapto("<Plug>ToggledebugMode", "n")
    nmap  <silent> <buffer> <LocalLeader><Localleader>d	<Plug>ToggledebugMode
endif
if !hasmapto("<Plug>ToggleDebugMode", "n")
    nmap  <silent> <buffer> <LocalLeader><Localleader>D	<Plug>ToggleDebugMode
endif
if !hasmapto("<Plug>WrapEnvironment", "v")
    vmap  <silent> <buffer> <F4>			<Plug>WrapEnvironment
endif
if !hasmapto("<Plug>ChangeEnv", "n")
    nmap  <silent> <buffer> <F4>			<Plug>ChangeEnv
endif
if !hasmapto("<Plug>ChangeEnv", "i")
    imap  <silent> <buffer> <F4>			<C-O><Plug>ChangeEnv
endif
if !hasmapto("<Plug>ToggleEnvForward", "n")
    nmap  <silent> <buffer> <S-F4>			<Plug>ToggleEnvForward
endif
"     ToDo:
"     if g:atp_LatexBox
" 	nmap <silent> <buffer> <F3>			:call <Sid>ChangeEnv()<CR>
"     endif
if !hasmapto("<Plug>ATP_ViewOutput", "n")
    nmap  <silent> <buffer> <F3>        		<Plug>ATP_ViewOutput_sync
    nmap  <silent> <buffer> <LocalLeader>v		<Plug>ATP_ViewOutput_nosync
endif
if !hasmapto("<Plug>ATP_ViewLocalOutput", "n")
    nmap  <silent> <buffer> <S-F3>        		<Plug>ATP_ViewLocalOutput_sync
    nmap  <silent> <buffer> <LocalLeader>V		<Plug>ATP_ViewLocalOutput_nosync
endif
if !hasmapto("<Plug>ATP_ViewOutput", "i")
    imap  <silent> <buffer> <F3> 			<C-O><Plug>ATP_ViewOutput_sync
endif
if !hasmapto("<Plug>ATP_ViewLocalOutput", "i")
    imap  <silent> <buffer> <S-F3> 			<C-O><Plug>ATP_ViewLocalOutput_sync
endif
if !hasmapto("<Plug>Getpid", "n")
    nmap  <silent> <buffer> <LocalLeader>g 		<Plug>Getpid
endif
if !hasmapto("<Plug>ATP_TOC", "n")
    nmap  <silent> <buffer> <LocalLeader>t		<Plug>ATP_TOC
endif
if !hasmapto("<Plug>ATP_Labels", "n")
    nmap  <silent> <buffer> <LocalLeader>L		<Plug>ATP_Labels
endif
if !hasmapto("<Plug>ATP_TeXCurrent", "n")
    nmap  <silent> <buffer> <LocalLeader>l 		<Plug>ATP_TeXCurrent
endif
if !hasmapto("<Plug>ATP_TeXLocal", "n")
    nmap <silent> <buffer> <LocalLeader>k		<Plug>ATP_TeXLocal
endif
if !hasmapto("<Plug>ATP_TeXdebug", "n")
    nmap  <silent> <buffer> <LocalLeader>d 		<Plug>ATP_TeXdebug
endif
if !hasmapto("<Plug>ATP_TeXDebug", "n")
    nmap  <silent> <buffer> <LocalLeader>D 		<Plug>ATP_TeXDebug
endif
" if !hasmapto("<Plug>ATP_MakeLatex", "n")
"      nmap           <buffer> <c-l>			<Plug>ATP_MakeLatex
" endif
"ToDo: imaps!
if !hasmapto("<Plug>ATP_TeXVerbose", "n")
    nmap  <silent> <buffer> <F5> 			<Plug>ATP_TeXVerbose
endif
if !hasmapto("<Plug>ToggleAuTeX", "n")
    nmap  <silent> <buffer> <s-F5> 				<Plug>ToggleAuTeX
endif
if !hasmapto("<Plug>ToggleAuTeXa", "i")
    imap  <silent> <buffer> <s-F5> 			<C-O><Plug>ToggleAuTeX
endif
if !hasmapto("<Plug>ToggleTab", "n") && g:atp_tab_map
    nmap  <silent> <buffer> `<Tab>			<Plug>ToggleTab
endif
if !hasmapto("<Plug>ToggleTab", "i") && g:atp_tab_map
    imap  <silent> <buffer> `<Tab>			<Plug>ToggleTab
endif
if !hasmapto("<Plug>ToggleIMaps", "n")
    nmap  <silent> <buffer> '<Tab>			<Plug>ToggleIMaps
endif
if !hasmapto("<Plug>ToggleIMapsa", "i")
    imap  <silent> <buffer> '<Tab>			<Plug>ToggleIMaps
endif
if !hasmapto("<Plug>SimpleBibtex", "n")
    nmap  <silent> <buffer> <LocalLeader>B		<Plug>SimpleBibtex
endif
if !hasmapto("<Plug>BibtexDefault", "n")
    nmap  <silent> <buffer> <LocalLeader>b		<Plug>BibtexDefault
endif
if !hasmapto("<Plug>Delete", "n")
    nmap  <silent> <buffer> <F6>d 			<Plug>Delete
endif
if !hasmapto("<Plug>Delete", "i")
    imap  <silent> <buffer> <F6>d			<C-O><Plug>Delete
endif
if !hasmapto("<Plug>OpenLog", "n")
    nmap  <silent> <buffer> <F6>l 			<Plug>OpenLog
endif
if !hasmapto("<Plug>OpenLog", "i")
    imap  <silent> <buffer> <F6>l 			<C-O><Plug>OpenLog
endif
if !hasmapto(":ShowErrors e<CR>", "n")
    nmap  <silent> <buffer> <F6> 			:ShowErrors e<CR>
endif
if !hasmapto(":ShowErrors e<CR>", "i")
    imap  <silent> <buffer> <F6> 			:ShowErrors e<CR>
endif
if !hasmapto(":ShowErrors<CR>", "n")
    nmap   <silent> <buffer> <LocalLeader>e		:ShowErrors<CR>
endif
if !hasmapto(":ShowErrors w<CR>", "n")
    nmap  <silent> <buffer> <F6>w 			:ShowErrors w<CR>
endif
if !hasmapto(":ShowErrors w<CR>", "i")
    imap  <silent> <buffer> <F6>w 			:ShowErrors w<CR>
endif
if !hasmapto(":ShowErrors rc<CR>", "n")
    nmap  <silent> <buffer> <F6>r 			:ShowErrors rc<CR>
endif
if !hasmapto(":ShowErrors rc<CR>", "i")
    imap  <silent> <buffer> <F6>r 			:ShowErrors rc<CR>
endif
if !hasmapto(":ShowErrors f<CR>", "n")
    nmap  <silent> <buffer> <F6>f 			:ShowErrors f<CR>
endif
if !hasmapto(":ShowErrors f<CR>", "i")
    imap  <silent> <buffer> <F6>f 			:ShowErrors f<CR>
endif
if !hasmapto("<Plug>PdfFonts", "n")
    nmap  <silent> <buffer> <F6>g 			<Plug>PdfFonts
endif

" TEXDOC: {{{2
" Note :TexDoc map cannot be <silent>
nnoremap           <buffer> <Plug>TexDoc		:TexDoc<space>
if !hasmapto("<Plug>TexDoc", "n")
    nmap           <buffer> <F1>			<Plug>TexDoc
endif
inoremap           <buffer> <Plug>iTexDoc		<C-O>:TexDoc<space>
if !hasmapto("<Plug>iTexDoc", "i")
    imap           <buffer> <F1> 			<Plug>iTexDoc
endif

" FONT IMAPS: {{{1
if g:atp_imap_leader_1 == "]" || g:atp_imap_leader_2 == "]" || g:atp_imap_leader_3 == "]" || g:atp_imap_leader_4 == "]" 
    inoremap <silent> <buffer> ]] ]
endif
if !exists("g:atp_imap_define_fonts")
    let g:atp_imap_define_fonts = 1
endif

let s:math_open = ( &filetype == "plaintex" ? "$" : (&l:cpoptions =~# "B" ? "\\" : "\\\\")."(" )
if !exists("g:atp_imap_fonts") || g:atp_reload_variables
    let g:atp_imap_fonts = []
    for font in [ 'rm', 'it', 'sf', 'bf', 'tt', 'normal']
	call add(g:atp_imap_fonts, 
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_2, font, '(atplib#IsInMath() ? "\\math'.font.'{}<Left>" : "\\text'.font.'{}<Left>" )' , "g:atp_imap_define_fonts", '\text'.font ])
    endfor
    for font in [ 'up', 'md', 'sl', 'sc' ]
	call add(g:atp_imap_fonts, 
	    \ [ 'inoremap', '<silent> <buffer>', g:atp_imap_leader_2, font, s:backslash.'text'.font.'{}<Left>', "g:atp_imap_define_fonts", '\text'.font.'{}']
	    \ )
    endfor
    call extend(g:atp_imap_fonts,  [
	    \ [ 'inoremap', '<silent> <buffer>', g:atp_imap_leader_2, 'te', 
		\ s:backslash.'text{}<Left>', "g:atp_imap_define_fonts", '\text{}'],
	    \ [ 'inoremap', '<silent> <buffer>', g:atp_imap_leader_2, 'em', 
		\ s:backslash.'emph{}<Left>', "g:atp_imap_define_fonts", '\emph{}'],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_2, 'bb', 
		\ '(atplib#IsInMath() ? "'.s:bbackslash.'mathbb{}<Left>" : ( &filetype == "plaintex" ? "$" : (&l:cpoptions =~# "B" ? "\\" : "\\\\")."(" )."'.s:bbackslash.'mathbb{}<Left>" )' , "g:atp_imap_define_fonts", '\mathbb' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_2, 'cal', 
		\ '(atplib#IsInMath() ? "'.s:bbackslash.'mathcal{}<Left>" : ( &filetype == "plaintex" ? "$" : (&l:cpoptions =~# "B" ? "\\" : "\\\\")."(" )."'.s:bbackslash.'mathcal{}<Left>" )' , "g:atp_imap_define_fonts", '\mathcal' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_2, 'cr', 
		\ '(atplib#IsInMath() ? "'.s:bbackslash.'mathscr{}<Left>" : ( &filetype == "plaintex" ? "$" : (&l:cpoptions =~# "B" ? "\\" : "\\\\")."(" )."'.s:bbackslash.'mathscr{}<Left>" )' , "g:atp_imap_define_fonts", '\mathscr' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_2, 'fr', 
		\ '(atplib#IsInMath() ? "'.s:bbackslash.'mathfrak{}<Left>" : ( &filetype == "plaintex" ? "$" : (&l:cpoptions =~# "B" ? "\\" : "\\\\")."(" )."'.s:bbackslash.'mathfrak{}<Left>" )' , "g:atp_imap_define_fonts", '\mathfrak' ],
	    \ [ 'inoremap', '<silent> <buffer>', g:atp_imap_leader_2, 'uf',
		\ s:backslash.'usefont{'.g:atp_font_encoding.'}{}{}{}<Left><Left><Left><Left><Left>', "g:atp_imap_define_fonts", 'usefont command']
	\ ])
    endif
    " Make Font Maps:
    call atplib#MakeMaps(g:atp_imap_fonts)
	    
" GREEK LETTERS: {{{1
if !exists("g:atp_imap_greek_letters") || g:atp_reload_variables
    let g:atp_imap_greek_letters= [
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'a', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'alpha" : g:atp_imap_leader_1."a" )' ,	 
		    \ "g:atp_imap_define_greek_letters", '\alpha' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'b', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'beta" : g:atp_imap_leader_1."b" )',	 
		    \ "g:atp_imap_define_greek_letters", '\beta' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'c', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'chi" : g:atp_imap_leader_1."c" )',	 
		    \ "g:atp_imap_define_greek_letters", '\chi' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'd', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'delta" : g:atp_imap_leader_1."d" )',	 
		    \ "g:atp_imap_define_greek_letters", '\delta' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'e', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'epsilon" : g:atp_imap_leader_1."e" )',	 
		    \ "g:atp_imap_define_greek_letters", '\epsilon' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'f', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'phi" : g:atp_imap_leader_1."f" )',	 
		    \ "g:atp_imap_define_greek_letters", '\phi' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'y', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'psi" : g:atp_imap_leader_1."y" )',	 
		    \ "g:atp_imap_define_greek_letters", '\psi' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'g', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'gamma" : g:atp_imap_leader_1."g" )',	 
		    \ "g:atp_imap_define_greek_letters", '\gamma' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'h', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'eta" : g:atp_imap_leader_1."h" )',	 
		    \ "g:atp_imap_define_greek_letters", '\eta' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'k', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'kappa" : g:atp_imap_leader_1."k" )',	 
		    \ "g:atp_imap_define_greek_letters", '\kappa' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'l', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'lambda" : g:atp_imap_leader_1."l" )',	 
		    \ "g:atp_imap_define_greek_letters", '\lambda' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'i', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'iota" : g:atp_imap_leader_1."i" )',	 
		    \ "g:atp_imap_define_greek_letters", '\iota' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'm', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'mu" : g:atp_imap_leader_1."m" )',	 
		    \ "g:atp_imap_define_greek_letters", '\mu' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'n', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'nu" : g:atp_imap_leader_1."n" )',	 
		    \ "g:atp_imap_define_greek_letters", '\nu' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'p', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'pi" : g:atp_imap_leader_1."p" )',	 
		    \ "g:atp_imap_define_greek_letters", '\pi' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'o', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'theta" : g:atp_imap_leader_1."o" )',	 
		    \ "g:atp_imap_define_greek_letters", '\theta' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'r', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'rho" : g:atp_imap_leader_1."r" )',	 
		    \ "g:atp_imap_define_greek_letters", '\rho' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 's', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'sigma" : g:atp_imap_leader_1."s" )',	 
		    \ "g:atp_imap_define_greek_letters", '\sigma' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 't', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'tau" : g:atp_imap_leader_1."t" )',	 
		    \ "g:atp_imap_define_greek_letters", '\tau' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'u', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'upsilon" : g:atp_imap_leader_1."u" )',	 
		    \ "g:atp_imap_define_greek_letters", '\upsilon' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'w', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'omega" : g:atp_imap_leader_1."w" )',	 
		    \ "g:atp_imap_define_greek_letters", '\omega' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'x', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'xi" : g:atp_imap_leader_1."x" )',	 
		    \ "g:atp_imap_define_greek_letters", '\xi' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'z', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'zeta" : g:atp_imap_leader_1."z" )',	 
		    \ "g:atp_imap_define_greek_letters", '\zeta' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 've', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'varepsilon" : g:atp_imap_leader_1."ve" )', 
		    \ "g:atp_imap_define_greek_letters", '\varepsilon' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'vs', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'varsigma" : g:atp_imap_leader_1."vs" )', 	 
		    \ "g:atp_imap_define_greek_letters", '\varsigma' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'vo', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'vartheta" : g:atp_imap_leader_1."vo" )',	 
		    \ "g:atp_imap_define_greek_letters", '\vartheta' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'vf', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'varphi" : g:atp_imap_leader_1."vf" )',	 
		    \ "g:atp_imap_define_greek_letters", '\varphi' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'vp', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'varpi" : g:atp_imap_leader_1."vp" )',	 
		    \ "g:atp_imap_define_greek_letters", '\varpi' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'X', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'Xi" : g:atp_imap_leader_1."X" )',	 
		    \ "g:atp_imap_define_greek_letters", '\Xi' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'D', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'Delta" : g:atp_imap_leader_1."D" )',	 
		    \ "g:atp_imap_define_greek_letters", '\Delta' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'Y', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'Psi" : g:atp_imap_leader_1."Y" )',	 
		    \ "g:atp_imap_define_greek_letters", '\Psi' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'F', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'Phi" : g:atp_imap_leader_1."F" )',	 
		    \ "g:atp_imap_define_greek_letters", '\Phi' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'G', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'Gamma" : g:atp_imap_leader_1."G" )',	 
		    \ "g:atp_imap_define_greek_letters", '\Gamma' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'L', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'Lambda" : g:atp_imap_leader_1."L" )',	 
		    \ "g:atp_imap_define_greek_letters", '\Lambda' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'P', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'Pi" : g:atp_imap_leader_1."P" )',	 
		    \ "g:atp_imap_define_greek_letters", '\Pi' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'O', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'Theta" : g:atp_imap_leader_1."O" )',	 
		    \ "g:atp_imap_define_greek_letters", '\Theta' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'S', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'Sigma" : g:atp_imap_leader_1."S" )',	 
		    \ "g:atp_imap_define_greek_letters", '\Sigma' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'U', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'Upsilon" : g:atp_imap_leader_1."U" )',	 
		    \ "g:atp_imap_define_greek_letters", '\Upsilon' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_leader_1, 'W', '(!atplib#IsLeft("\\")&& atplib#IsInMath() ? "'.s:bbackslash.'Omega" : g:atp_imap_leader_1."W" )',	 
		    \ "g:atp_imap_define_greek_letters", '\Omega' ],
	    \ ]
endif

    " Make Greek Letters:
    augroup ATP_MathIMaps_GreekLetters
	au!
" 	au CursorMovedI	*.tex 	:call atplib#ToggleIMaps(g:atp_imap_greek_letters, 'CursorMovedI', [], 1)
	au CursorHoldI 	*.tex 	:call atplib#ToggleIMaps(g:atp_imap_greek_letters, 'CursorHoldI')
	au InsertEnter	*.tex 	:call atplib#ToggleIMaps(g:atp_imap_greek_letters, 'InsertEnter') 
	" Make imaps visible with :imap /this will not work with i_CTRL-C/
" 	au InsertLeave	*.tex 	:call atplib#MakeMaps(g:atp_imap_greek_letters, 'InsertLeave')
	au BufEnter	*.tex 	:call atplib#MakeMaps(g:atp_imap_greek_letters, 'BufEnter')
    augroup END

" MISCELLANEOUS MATHEMATICAL MAPS: {{{1
if !exists("g:atp_imap_math_misc") || g:atp_reload_variables
let g:atp_imap_math_misc = [
\ [ 'inoremap', '<silent> <buffer> <expr>', '+',	      '+', 
	\ '!atplib#IsLeft("^")&&!atplib#IsLeft("_") ? '''.s:backslash.'sum'' : "++"',
	\ "g:atp_imap_define_math_misc", '\sum' ],
\ [ 'inoremap', '<silent> <buffer>', '<bar>', 		      '-', s:backslash.'vdash',
	\ "g:atp_imap_define_math_misc", '\vdash' ],
\ [ 'inoremap', '<silent> <buffer>', '-', 		      '<bar>', s:backslash.'dashv',
	\ "g:atp_imap_define_math_misc", '\dashv' ],
\ [ 'inoremap', '<silent> <buffer>', g:atp_infty_leader,      '8', s:backslash.'infty', 	
	\ "g:atp_imap_define_math_misc", '\infty' ],
\ [ 'inoremap', '<silent> <buffer>', g:atp_infty_leader,      '6', s:backslash.'partial',	
	\ "g:atp_imap_define_math_misc", '\partial' ],
\ [ 'inoremap', '<silent> <buffer>', g:atp_imap_leader_1, '&', s:backslash.'wedge', 	
	\ "g:atp_imap_define_math_misc", '\wedge' ], 
\ [ 'inoremap', '<silent> <buffer>', g:atp_imap_leader_1, '+', s:backslash.'bigcup', 	
	\ "g:atp_imap_define_math_misc", '\bigcup' ],
\ [ 'inoremap', '<silent> <buffer>', g:atp_imap_leader_1, '*', s:backslash.'bigcap', 	
	\ "g:atp_imap_define_math_misc", '\bigcap' ],
\ [ 'inoremap', '<silent> <buffer>', g:atp_imap_leader_1, 'N', s:backslash.'Nabla', 	
	\ "g:atp_imap_define_math_misc", '\Nabla' ],
\ [ 'inoremap', '<silent> <buffer>', g:atp_imap_leader_1, '@', s:backslash.'circ', 	
	\ "g:atp_imap_define_math_misc", '\circ' ],
\ [ 'inoremap', '<silent> <buffer>', g:atp_imap_leader_1, '=', s:backslash.'equiv', 	
	\ "g:atp_imap_define_math_misc", '\equiv' ],
\ [ 'inoremap', '<silent> <buffer>', g:atp_imap_leader_1, '.', s:backslash.'dot', 
	\ "g:atp_imap_define_math_misc", '\dot' ],
\ [ 'inoremap', '<silent> <buffer>', g:atp_imap_leader_1, '/', s:backslash.'frac{}{}<Esc>F}i',
	\ "g:atp_imap_define_math_misc", '\frac{}{}' ],
\ [ 'inoremap', '<silent> <buffer>', g:atp_imap_over_leader,  '`', s:backslash.'grave{}<Left>',
	\ "g:atp_imap_define_math_misc", '\grave{}' ],
\ [ 'inoremap', '<silent> <buffer>', g:atp_imap_over_leader,  'v', s:backslash.'check{}<Left>',
	\ "g:atp_imap_define_math_misc", '\check{}' ],
\ [ 'inoremap', '<silent> <buffer>', g:atp_imap_over_leader,  '''', s:backslash.'acute{}<Left>',
	\ "g:atp_imap_define_math_misc", '\acute{}' ],
\ [ 'inoremap', '<silent> <buffer>', g:atp_imap_over_leader,  '.', s:backslash.'dot{}<Left>',
	\ "g:atp_imap_define_math_misc", '\dot{}' ],
\ [ 'inoremap', '<silent> <buffer>', g:atp_imap_over_leader,  '>', s:backslash.'vec{}<Left>',
	\ "g:atp_imap_define_math_misc", '\vec{}' ],
\ [ 'inoremap', '<silent> <buffer>', g:atp_imap_over_leader,  '_', s:backslash.'bar{}<Left>',
	\ "g:atp_imap_define_math_misc", '\bar{}' ],
\ [ 'inoremap', '<silent> <buffer>', g:atp_imap_over_leader,  '~', s:backslash.'=(g:atp_imap_wide ? "wide" : "")<CR>tilde{}<Left>',
	\ "g:atp_imap_define_math_misc", '''\''.(g:atp_imap_wide ? "wide" : "")."tilde"' ],
\ [ 'inoremap', '<silent> <buffer>', g:atp_imap_over_leader,  '^', s:backslash.'=(g:atp_imap_wide ? "wide" : "" )<CR>hat{}<Left>',
	\ "g:atp_imap_define_math_misc", '''\''.(g:atp_imap_wide ? "wide" : "")."hat"' ], 
\ [ 'inoremap', '<silent> <buffer>', g:atp_imap_leader_2,  'ov', s:backslash.'overline{}<Left>',
	\ "g:atp_imap_define_math_misc", '\overline{}' ],
\ [ 'inoremap', '<silent> <buffer>', g:atp_imap_leader_2,  'un', s:backslash.'underline{}<Left>',
	\ "g:atp_imap_define_math_misc", '\underline{}' ],
\ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_over_leader,  	      'D', '"<ESC>vx".(col(".")<=len(getline("."))? "i" : "a" )."'.s:bbackslash.'frac{'.s:bbackslash.'partial}{'.s:bbackslash.'partial \"}".(g:atp_imap_diffop_move ? "<C-o>F}<space>" : "")', 
	\ "g:atp_imap_define_math_misc", '\frac{\partial}{\partial x} - x comes from the letter wrote just before' ]
\ ]
" These two maps where interfering with \varepsilon
" \ [ 'inoremap', '<silent> <buffer>', g:atp_imap_leader_1, 've', s:backslash.'vee',
" 	\ "g:atp_imap_define_math_misc", '\vee' ],
" \ [ 'inoremap', '<silent> <buffer>', g:atp_imap_leader_1, 'V', s:backslash.'bigvee',
" 	\ "g:atp_imap_define_math_misc", '\Vee' ],

" " 		\ [ 'inoremap', '<silent> <buffer>', g:atp_imap_leader_1, '~', s:backslash.'=(g:atp_imap_wide ? "wide" : "")<CR>tilde{}<Left>', 	"g:atp_imap_define_math_misc", '''\''.(g:atp_imap_wide ? "wide" : "")."tilde"' ],
" 		\ [ 'inoremap', '<silent> <buffer>', g:atp_imap_leader_1, '^', s:backslash.'=(g:atp_imap_wide ? "wide" : "" )<CR>hat{}<Left>', 	"g:atp_imap_define_math_misc", '''\''.(g:atp_imap_wide ? "wide" : "")."hat"' ], 
endif

    " Make Miscellaneous Mathematical Maps:
    augroup ATP_MathIMaps_misc
	au!
	au CursorHoldI 	*.tex 	:call atplib#ToggleIMaps(g:atp_imap_math_misc, 'CursorHoldI', g:atp_imap_diacritics) 
	au InsertEnter	*.tex 	:call atplib#ToggleIMaps(g:atp_imap_math_misc, 'InsertEnter', g:atp_imap_diacritics) 
    augroup END

" DIACRITICSC IMAPS: {{{1
    if g:atp_diacritics == 2
	let g:atp_imap_diacritics = [
	    \ [ 'inoremap', '<silent> <buffer>', g:atp_imap_over_leader,  '''', s:backslash.'''{}<Left>',
		    \ "g:atp_imap_define_diacritics", '\''{}' ],
	    \ [ 'inoremap', '<silent> <buffer>', g:atp_imap_over_leader,  '"', s:backslash.'"{}<Left>',
		    \ "g:atp_imap_define_diacritics", '\"{}' ],
	    \ [ 'inoremap', '<silent> <buffer>', g:atp_imap_over_leader,  '2', s:backslash.'"{}<Left>',
		    \ "g:atp_imap_define_diacritics", '\"{}' ],
	    \ [ 'inoremap', '<silent> <buffer>', g:atp_imap_over_leader,  '^', s:backslash.'^{}<Left>',
		    \ "g:atp_imap_define_diacritics", '\^{}' ],
	    \ [ 'inoremap', '<silent> <buffer>', g:atp_imap_over_leader,  'v', s:backslash.'v{}<Left>',
		    \ "g:atp_imap_define_diacritics", '\v{}' ],
	    \ [ 'inoremap', '<silent> <buffer>', g:atp_imap_over_leader,  'b', s:backslash.'b{}<Left>',
		    \ "g:atp_imap_define_diacritics", '\b{}' ],
	    \ [ 'inoremap', '<silent> <buffer>', g:atp_imap_over_leader,  'd', s:backslash.'d{}<Left>',
		    \ "g:atp_imap_define_diacritics", '\d{}' ],
	    \ [ 'inoremap', '<silent> <buffer>', g:atp_imap_over_leader,  '`', s:backslash.'`{}<Left>',
		    \ "g:atp_imap_define_diacritics", '\`{}' ],
	    \ [ 'inoremap', '<silent> <buffer>', g:atp_imap_over_leader,  'H', s:backslash.'H{}<Left>',
		    \ "g:atp_imap_define_diacritics", '\H{}' ],
	    \ [ 'inoremap', '<silent> <buffer>', g:atp_imap_over_leader,  '~', s:backslash.'~{}<Left>',
		    \ "g:atp_imap_define_diacritics", '\~{}' ],
	    \ [ 'inoremap', '<silent> <buffer>', g:atp_imap_over_leader,  '.', s:backslash.'.{}<Left>',
		    \ "g:atp_imap_define_diacritics", '\.{}' ],
	    \ [ 'inoremap', '<silent> <buffer>', g:atp_imap_over_leader,  'c', s:backslash.'c{}<Left>',
		    \ "g:atp_imap_define_diacritics", '\c{}' ],
	    \ [ 'inoremap', '<silent> <buffer>', g:atp_imap_over_leader,  't', s:backslash.'t{}<Left>',
		    \ "g:atp_imap_define_diacritics", '\t{}' ]
	    \ ]

    elseif g:atp_diacritics
	let g:atp_imap_diacritics = [
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_over_leader,  '''', '(index(split(g:atp_diacritics_letters["''"], ''\zs''), tolower(getline(line("."))[col(".")-2])) != -1  ? "<ESC>vx".(col(".")<=len(getline(line(".")))? "i" : "a" )."'.s:bbackslash.'''{\"}" : "'.escape(g:atp_imap_over_leader, '\"').'''")', 
		    \ "g:atp_imap_define_diacritics", '\''{}' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_over_leader,  '"', '(index(split(g:atp_diacritics_letters[''"''], ''\zs''), tolower(getline(line("."))[col(".")-2])) != -1  ? "<ESC>vx".(col(".")<=len(getline("."))? "i" : "a" )."'.s:bbackslash.'\"{\"}" : "'.escape(g:atp_imap_over_leader, '\"').'\"")',
		    \ "g:atp_imap_define_diacritics", '\"{}' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_over_leader,  '2', '(index(split(g:atp_diacritics_letters[''2''], ''\zs''), tolower(getline(line("."))[col(".")-2])) != -1 ? "<ESC>vx".(col(".")<=len(getline("."))? "i" : "a" )."'.s:bbackslash.'2{\"}" : "'.escape(g:atp_imap_over_leader, '\"').'2")',
		    \ "g:atp_imap_define_diacritics", '\2{}' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_over_leader,  '^', '(index(split(g:atp_diacritics_letters[''^''], ''\zs''), tolower(getline(line("."))[col(".")-2])) != -1 ? "<ESC>vx".(col(".")<=len(getline("."))? "i" : "a" )."'.s:bbackslash.'^{\"}" : "'.escape(g:atp_imap_over_leader, '\"').'^")',
		    \ "g:atp_imap_define_diacritics", '\^{}' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_over_leader,  'v', '(index(split(g:atp_diacritics_letters[''v''], ''\zs''), tolower(getline(line("."))[col(".")-2])) != -1 ? "<ESC>vx".(col(".")<=len(getline("."))? "i" : "a" )."'.s:bbackslash.'v{\"}" : "'.escape(g:atp_imap_over_leader, '\"').'v" )',
		    \ "g:atp_imap_define_diacritics", '\v{}' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_over_leader,  'b', '(index(split(g:atp_diacritics_letters[''b''], ''\zs''), tolower(getline(line("."))[col(".")-2])) != -1 ? "<ESC>vx".(col(".")<=len(getline("."))? "i" : "a" )."'.s:bbackslash.'b{\"}" : "'.escape(g:atp_imap_over_leader, '\"').'b" )',
		    \ "g:atp_imap_define_diacritics", '\b{}' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_over_leader,  'd', '(index(split(g:atp_diacritics_letters[''d''], ''\zs''), tolower(getline(line("."))[col(".")-2])) != -1 ? "<ESC>vx".(col(".")<=len(getline("."))? "i" : "a" )."'.s:bbackslash.'d{\"}" : "'.escape(g:atp_imap_over_leader, '\"').'d" )',
		    \ "g:atp_imap_define_diacritics", '\d{}' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_over_leader,  '`', '(index(split(g:atp_diacritics_letters[''`''], ''\zs''), tolower(getline(line("."))[col(".")-2])) != -1 ? "<ESC>vx".(col(".")<=len(getline("."))? "i" : "a" )."'.s:bbackslash.'`{\"}" : "'.escape(g:atp_imap_over_leader, '\"').'`" )',
		    \ "g:atp_imap_define_diacritics", '\`{}' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_over_leader,  'H', '(index(split(g:atp_diacritics_letters[''H''], ''\zs''), tolower(getline(line("."))[col(".")-2])) != -1 ? "<ESC>vx".(col(".")<=len(getline("."))? "i" : "a" )."'.s:bbackslash.'H{\"}" : "'.escape(g:atp_imap_over_leader, '\"').'H" )',
		    \ "g:atp_imap_define_diacritics", '\H{}' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_over_leader,  '~', '(index(split(g:atp_diacritics_letters[''~''], ''\zs''), tolower(getline(line("."))[col(".")-2])) != -1 ?"<ESC>vx".(col(".")<=len(getline("."))? "i" : "a" )."'.s:bbackslash.'~{\"}" : "'.escape(g:atp_imap_over_leader, '\"').'~" )',
		    \ "g:atp_imap_define_diacritics", '\~{}' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_over_leader,  '.', '(index(split(g:atp_diacritics_letters[''.''], ''\zs''), tolower(getline(line("."))[col(".")-2])) != -1 ?"<ESC>vx".(col(".")<=len(getline("."))? "i" : "a" )."'.s:bbackslash.'.{\"}" : "'.escape(g:atp_imap_over_leader, '\"').'." )',
		    \ "g:atp_imap_define_diacritics", '\.{}' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_over_leader,  'c', '(index(split(g:atp_diacritics_letters[''c''], ''\zs''), tolower(getline(line("."))[col(".")-2])) != -1 ?"<ESC>vx".(col(".")<=len(getline("."))? "i" : "a" )."'.s:bbackslash.'c{\"}" : "'.escape(g:atp_imap_over_leader, '\"').'c" )',
		    \ "g:atp_imap_define_diacritics", '\c{}' ],
	    \ [ 'inoremap', '<silent> <buffer> <expr>', g:atp_imap_over_leader,  't', '(index(split(g:atp_diacritics_letters[''t''], ''\zs''), tolower(getline(line("."))[col(".")-2])) != -1 ? "<ESC>vx".(col(".")<=len(getline("."))? "i" : "a" )."'.s:bbackslash.'t{\"}" : "'.escape(g:atp_imap_over_leader, '\"').'t" )',
		    \ "g:atp_imap_define_diacritics", '\t{}' ]
	    \ ]
    else
	let g:atp_imap_diacritics=[]
    endif

" ENVIRONMENT MAPS: {{{1
if g:atp_no_env_maps != 1
    if !exists("g:atp_imap_environments") || g:atp_reload_variables
    let g:atp_imap_environments = [
	\ [ "inoremap", "<buffer> <silent>", 	g:atp_imap_leader_3, "m", 			s:backslash.'('.s:backslash.')<Left><Left>', 						"g:atp_imap_define_environments", 'inlince math' ],
	\ [ "inoremap", "<buffer> <silent>", 	g:atp_imap_leader_3, "M", 			s:backslash.'['.s:backslash.']<Left><Left>', 						"g:atp_imap_define_environments", 'displayed math' ],
	\ [ 'inoremap', '<silent> <buffer>',	g:atp_imap_leader_3, g:atp_imap_begin, 		s:backslash.'begin{}<Left>', 						"g:atp_imap_define_environments", '\begin{}' ],
	\ [ 'inoremap', '<silent> <buffer>',	g:atp_imap_leader_3, g:atp_imap_end, 		s:backslash.'end{}<Left>', 						"g:atp_imap_define_environments", '\end{}' ],
	\ [ 'inoremap', '<silent> <buffer>',	g:atp_imap_leader_3, g:atp_imap_proof, 		s:backslash.'begin{proof}<CR>'.s:backslash.'end{proof}<Esc>O', 				"g:atp_imap_define_environments", 'proof' ],
	\ [ 'inoremap', '<silent> <buffer>',	g:atp_imap_leader_3, g:atp_imap_center, 	s:backslash.'begin{center}<CR>\end{center}<Esc>O', 			"g:atp_imap_define_environments", 'center' ],
	\ [ 'inoremap', '<silent> <buffer>',	g:atp_imap_leader_3, g:atp_imap_flushleft, 	s:backslash.'begin{flushleft}<CR>'.s:backslash.'end{flushleft}<Esc>O', 			"g:atp_imap_define_environments", 'flushleft' ],
	\ [ 'inoremap', '<silent> <buffer>',	g:atp_imap_leader_3, g:atp_imap_flushright, 	s:backslash.'begin{flushright}<CR>'.s:backslash.'end{flushright}<Esc>O', 		"g:atp_imap_define_environments", 'flushright' ],
	\ [ 'inoremap', '<silent> <buffer>',	g:atp_imap_leader_3, g:atp_imap_bibliography, 	s:backslash.'begin{thebibliography}<CR>'.s:backslash.'end{thebibliography}<Esc>O', 	"g:atp_imap_define_environments", 'bibliography' ],
	\ [ 'inoremap', '<silent> <buffer>',	g:atp_imap_leader_3, g:atp_imap_abstract, 	s:backslash.'begin{abstract}<CR>'.s:backslash.'end{abstract}<Esc>O', 			"g:atp_imap_define_environments", 'abstract' ],
	\ [ 'inoremap', '<silent> <buffer>',	g:atp_imap_leader_3, g:atp_imap_item, 		'<Esc>:call InsertItem()<CR>a', 				"g:atp_imap_define_environments", 'item' 	],
	\ [ 'inoremap', '<silent> <buffer>',	g:atp_imap_leader_3, g:atp_imap_frame, 		s:backslash.'begin{frame}<CR>'.s:backslash.'end{frame}<Esc>O', 				"g:atp_imap_define_environments", 'frame' ],
	\ [ 'inoremap', '<silent> <buffer>',	g:atp_imap_leader_3, g:atp_imap_enumerate, 	s:backslash.'begin{enumerate}'.g:atp_EnvOptions_enumerate.'<CR>'.s:backslash.'end{enumerate}<Esc>O'.s:backslash.'item', 	"g:atp_imap_define_environments", 'enumerate' ],
	\ [ 'inoremap', '<silent> <buffer>',	g:atp_imap_leader_3, g:atp_imap_tabular, 	s:backslash.'end{tabular}<Esc>O'.s:backslash.'begin{tabular}{}<Left>', 	"g:atp_imap_define_environments", 'tabular' ],
	\ [ 'inoremap', '<silent> <buffer>',	g:atp_imap_leader_3, g:atp_imap_table, 		s:backslash.'end{table}<Esc>O<C-T>'.s:backslash.'caption{}<Esc>O'.s:backslash.'begin{table}<CR>'.s:backslash.'end{tabular}<C-T><Esc>O'.s:backslash.'begin{tabular}{}<Left>', 	"g:atp_imap_define_environments", 'tabular' ],
	\ [ 'inoremap', '<silent> <buffer>',	g:atp_imap_leader_3, g:atp_imap_itemize, 	s:backslash.'begin{itemize}'.g:atp_EnvOptions_itemize.'<CR>'.s:backslash.'end{itemize}<Esc>O'.s:backslash.'item', 		"g:atp_imap_define_environments", 'itemize' ],
	\ [ 'inoremap', '<silent> <buffer>',	g:atp_imap_leader_3, g:atp_imap_tikzpicture, 	s:backslash.'begin{center}<CR>'.s:backslash.'begin{tikzpicture}<CR>'.s:backslash.'end{tikzpicture}<CR>'.s:backslash.'end{center}<Up><Esc>O', "g:atp_imap_define_environments", 'tikzpicture' ],
	\ [ 'inoremap', '<silent> <buffer>',	g:atp_imap_leader_3, g:atp_imap_theorem, 	s:backslash.'begin{=g:atp_EnvNameTheorem<CR>=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)<CR>}<CR>'.s:backslash.'end{=g:atp_EnvNameTheorem<CR>=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)<CR>}<Esc>O',  	"g:atp_imap_define_environments", 'theorem'],
	\ [ 'inoremap', '<silent> <buffer>',	g:atp_imap_leader_3, g:atp_imap_definition, 	s:backslash.'begin{=g:atp_EnvNameDefinition<CR>=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)<CR>}<CR>'.s:backslash.'end{=g:atp_EnvNameDefinition<CR>=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)<CR>}<Esc>O', 	"g:atp_imap_define_environments", 'definition'],
	\ [ 'inoremap', '<silent> <buffer>',	g:atp_imap_leader_3, g:atp_imap_proposition, 	s:backslash.'begin{=g:atp_EnvNameProposition<CR>=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)<CR>}<CR>'.s:backslash.'end{=g:atp_EnvNameProposition<CR>=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)<CR>}<Esc>O', 	"g:atp_imap_define_environments", 'proposition' ],
	\ [ 'inoremap', '<silent> <buffer>',	g:atp_imap_leader_3, g:atp_imap_lemma, 		s:backslash.'begin{=g:atp_EnvNameLemma<CR>=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)<CR>}<CR>'.s:backslash.'end{=g:atp_EnvNameLemma<CR>=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)<CR>}<Esc>O', 		"g:atp_imap_define_environments", 'lemma' ],
	\ [ 'inoremap', '<silent> <buffer>',	g:atp_imap_leader_3, g:atp_imap_remark, 	s:backslash.'begin{=g:atp_EnvNameRemark<CR>=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)<CR>}<CR>'.s:backslash.'end{=g:atp_EnvNameRemark<CR>=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)<CR>}<Esc>O', 		"g:atp_imap_define_environments", 'remark' ],
	\ [ 'inoremap', '<silent> <buffer>',	g:atp_imap_leader_3, g:atp_imap_note, 		s:backslash.'begin{=g:atp_EnvNameNote<CR>=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)<CR>}<CR>'.s:backslash.'end{=g:atp_EnvNameNote<CR>=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)<CR>}<Esc>O', 		"g:atp_imap_define_environments", 'note' ],
	\ [ 'inoremap', '<silent> <buffer>',	g:atp_imap_leader_3, g:atp_imap_example, 	s:backslash.'begin{=g:atp_EnvNameExample<CR>=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)<CR>}<CR>'.s:backslash.'end{=g:atp_EnvNameExample<CR>=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)<CR>}<Esc>O', 		"g:atp_imap_define_environments", 'example' ],
	\ [ 'inoremap', '<silent> <buffer>',	g:atp_imap_leader_3, g:atp_imap_corollary, 	s:backslash.'begin{=g:atp_EnvNameCorollary<CR>=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)<CR>}<CR>'.s:backslash.'end{=g:atp_EnvNameCorollary<CR>=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)<CR>}<Esc>O', 	"g:atp_imap_define_environments", 'corollary' ],
	\ [ 'inoremap', '<silent> <buffer>',	g:atp_imap_leader_3, g:atp_imap_align, 		s:backslash.'begin{align=(getline(".")[col(".")-2]=="*"?"":b:atp_StarMathEnvDefault)<CR>}<CR>'.s:backslash.'end{align=(getline(".")[col(".")-2]=="*"?"":b:atp_StarMathEnvDefault)<CR>}<Esc>O', 	"g:atp_imap_define_environments", 'align' ],
	\ [ 'inoremap', '<silent> <buffer>',	g:atp_imap_leader_3, g:atp_imap_multiline, 	s:backslash.'begin{multiline=(getline(".")[col(".")-2]=="*"?"":b:atp_StarMathEnvDefault)<CR>}<CR>'.s:backslash.'end{multiline=(getline(".")[col(".")-2]=="*"?"":b:atp_StarMathEnvDefault)<CR>}<Esc>O', 	"g:atp_imap_define_environments", 'multiline' ],
	\ [ 'inoremap', '<silent> <buffer>',	g:atp_imap_leader_3, g:atp_imap_equation, 	s:backslash.'begin{equation=(getline(".")[col(".")-2]=="*"?"":b:atp_StarMathEnvDefault)<CR>}<CR>'.s:backslash.'end{equation=(getline(".")[col(".")-2]=="*"?"":b:atp_StarMathEnvDefault)<CR>}<Esc>O', 	"g:atp_imap_define_environments", 'equation' ],
	\ [ 'inoremap', '<silent> <buffer>',	g:atp_imap_leader_3, g:atp_imap_letter, 	s:backslash.'begin{letter}{}<CR>'.s:backslash.'opening{=g:atp_letter_opening<CR>}<CR>'.s:backslash.'closing{=g:atp_letter_closing<CR>}<CR>'.s:backslash.'end{letter}<Esc>?'.s:bbackslash.'begin{letter}{'.s:backslash.'zs<CR>i', 				"g:atp_imap_define_environments", 'letter' ],
	\ ]
    endif
    " Make Environment Maps:
    call atplib#MakeMaps(g:atp_imap_environments)
endif


" MATHEMATICAL MAPS: {{{1
if !exists("g:atp_imap_math") || g:atp_reload_variables
    let g:atp_imap_math	= [ 
	\ [ "inoremap", "<buffer> <silent> <expr>", "", g:atp_imap_subscript, "( g:atp_imap_subscript == '_' && !atplib#IsLeft('\\', 1) && atplib#IsLeft('_') <bar><bar> g:atp_imap_subscript != '_' ) && atplib#IsInMath() ? (g:atp_imap_subscript == '_' ? '<BS>' : '' ).'_{}<Left>' : '_'", "g:atp_imap_define_math", 	'_{}'], 
	\ [ "inoremap", "<buffer> <silent> <expr>", "", g:atp_imap_supscript, "( g:atp_imap_supscript == '^' && !atplib#IsLeft('\\', 1) && atplib#IsLeft('^') <bar><bar> g:atp_imap_supscript != '^' ) && atplib#IsInMath() ? (g:atp_imap_supscript == '^' ? '<BS>' : '' ).'^{}<Left>' : (atplib#IsLeft('~') ? '<BS>".s:backslash."=(g:atp_imap_wide ? ''wide'' : '''' )<CR>hat{}<Left>' : '^')", "g:atp_imap_define_math", 	'^{}'],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "~", "atplib#IsLeft('~') && atplib#IsInMath() ? '<BS>".s:backslash."=(g:atp_imap_wide ? \"wide\" : \"\" ) <CR>tilde=(g:atp_imap_tilde_braces ? \"{}\" : \"\")<CR>'.(g:atp_imap_tilde_braces ? '<Left>' : '') : '~'" , "g:atp_imap_define_math", 	'\\(wide)tilde({})'], 
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "=", "atplib#IsInMath() && atplib#IsLeft('=') && !atplib#IsLeft('&',1) ? '<BS>&=' : '='", "g:atp_imap_define_math",	'&=' ],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "o+", "atplib#IsInMath() ? '".s:backslash."oplus' 	: 'o+'", "g:atp_imap_define_math", 		'\\oplus' ],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "O+", "atplib#IsInMath() ? '".s:backslash."bigoplus' 	: 'O+'", "g:atp_imap_define_math",		'\\bigoplus'],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "o-", "atplib#IsInMath() ? '".s:backslash."ominus' 	: 'o-'", "g:atp_imap_define_math",		'\\ominus'],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "o.", "atplib#IsInMath() ? '".s:backslash."odot' 	: 'o.'", "g:atp_imap_define_math",		'\\odot'],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "O.", "atplib#IsInMath() ? '".s:backslash."bigodot' 	: 'O.'", "g:atp_imap_define_math",		'\\bigodot'],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "o*", "atplib#IsInMath() ? '".s:backslash."otimes' 	: 'o*'", "g:atp_imap_define_math",		'\\otimes'],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "O*", "atplib#IsInMath() ? '".s:backslash."bigotimes' 	: 'O*'", "g:atp_imap_define_math",		'\\bigotimes'],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "t*", "atplib#IsInMath() ? '".s:backslash."times' 	: 't*'", "g:atp_imap_define_math",		'\\otimes'],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "s+", "atplib#IsInMath() ? '".s:backslash."cup' 	: 's+'", "g:atp_imap_define_math",		'\\cup'],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "s-", "atplib#IsInMath() ? '".s:backslash."setminus' 	: 's-'", "g:atp_imap_define_math",		'\\cup'],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "S+", "atplib#IsInMath() ? '".s:backslash."bigcup' 	: 'S+'", "g:atp_imap_define_math",		'\\bigcup'],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "s*", "atplib#IsInMath() ? '".s:backslash."cap' 	: 's*'", "g:atp_imap_define_math",		'\\cap'],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "S*", "atplib#IsInMath() ? '".s:backslash."bigcap' 	: 'S*'", "g:atp_imap_define_math",		'\\bigcap'],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "l*", "atplib#IsInMath() ? '".s:backslash."wedge' 	: 'l*'", "g:atp_imap_define_math",		'\\wedge'],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "L*", "atplib#IsInMath() ? '".s:backslash."bigwedge' 	: 'L*'", "g:atp_imap_define_math",		'\\bigwedge'],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "l+", "atplib#IsInMath() ? '".s:backslash."vee' 	: 'l+'", "g:atp_imap_define_math",		'\\vee'],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "L+", "atplib#IsInMath() ? '".s:backslash."bigvee' 	: 'L+'", "g:atp_imap_define_math",		'\\bigvee'],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "c*", "atplib#IsInMath() ? '".s:backslash."prod' 	: 'c*'", "g:atp_imap_define_math",		'\\prod'],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "c+", "atplib#IsInMath() ? '".s:backslash."coprod' 	: 'c+'", "g:atp_imap_define_math",		'\\coprod'],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "t<", "atplib#IsInMath() ? '".s:backslash."triangleleft' : 't<'", "g:atp_imap_define_math",		'\\triangleleft'],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "t>", "atplib#IsInMath() ? '".s:backslash."triangleright' : 't>'", "g:atp_imap_define_math",		'\\triangleright'],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "s<", "atplib#IsInMath() ? '".s:backslash."subseteq' 	: 's<'", "g:atp_imap_define_math",		'\\subseteq'],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "s>", "atplib#IsInMath() ? '".s:backslash."supseteq' 	: 's>'", "g:atp_imap_define_math",		'\\supseteq'],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "<=", "atplib#IsInMath() ? '".s:backslash."leq' 	: '<='", "g:atp_imap_define_math",		'\\leq'],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", ">=", "atplib#IsInMath() ? '".s:backslash."geq' 	: '>='", "g:atp_imap_define_math",		'\\geq'],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "#<", "atplib#IsInMath() ? '".s:backslash."langle' 	: '#<'", "g:atp_imap_define_math",		'\\langle'],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "#>", "atplib#IsInMath() ? '".s:backslash."rangle' 	: '#>'", "g:atp_imap_define_math",		'\\rangle'],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "->", "atplib#IsInMath('!') ? '".s:backslash."rightarrow' 	: ( atplib#complete#CheckSyntaxGroups(['texMathZoneT']) && getline('.')[1:col('.')] !~ '\\[[^\\]]*$' ? '\\draw[->]' : '->' )", "g:atp_imap_define_math",		'\\rightarrow'],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "<-", "atplib#IsInMath('!') ? '".s:backslash."leftarrow' 	: ( atplib#complete#CheckSyntaxGroups(['texMathZoneT']) && getline('.')[1:col('.')] !~ '\\[[^\\]]*$' ? '\\draw[<-]' : '<-' )", "g:atp_imap_define_math",		'\\leftarrow'],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "<_", "atplib#IsInMath('!') ? '".s:backslash."Leftarrow' 	: '<-'", "g:atp_imap_define_math",		'\\Leftarrow'],
	\ [ "inoremap", "<buffer> <silent> <expr>", "", "_>", "atplib#IsInMath('!') ? '".s:backslash."Rightarrow' 	: '->'", "g:atp_imap_define_math",		'\\Rightarrow'],
	\ ]
endif

" MAKE MATHEMATICAL MAPS: (autocommands) "{{{1
augroup ATP_MathIMaps
    au!
    au CursorHoldI 	*.tex 	:call atplib#ToggleIMaps(g:atp_imap_math, 'CursorHoldI')
    au InsertEnter	*.tex 	:call atplib#ToggleIMaps(g:atp_imap_math, 'InsertEnter')
    " Make imaps visible with :imap  /this will not work with i_CTRL-C/
"     au InsertLeave	*.tex 	:call atplib#MakeMaps(g:atp_imap_math, 'InsertLeave')
    au BufEnter		*.tex 	:call atplib#MakeMaps(g:atp_imap_math, 'BufEnter')
augroup END

augroup ATP_IMaps_CursorMovedI
    au CursorMovedI *.tex 	:call atplib#ToggleIMaps(g:atp_imap_greek_letters+g:atp_imap_math_misc
		\ +g:atp_imap_math, 'CursorMovedI', g:atp_imap_diacritics, 1)
augroup END
" }}}1
" vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1:nowrap
ftplugin/ATP_files/menu.vim	[[[1
280
" Author:	Marcin Szamotulski
" Description:	This file sets up the menu.
" Note:		This file is a part of Automatic Tex Plugin for Vim.
" Language:	tex
" Last Change:

let s:sourced = ( !exists("s:sourced") ? 0 : 1 )
if s:sourced
    finish
endif

let Compiler	= get(g:CompilerMsg_Dict, matchstr(b:atp_TexCompiler, '^\s*\zs\S*'), 'Compile')

let Viewer	= get(g:ViewerMsg_Dict, matchstr(b:atp_Viewer, '^\s*\zs\S*'), "")

if !exists("no_plugin_menu") && !exists("no_atp_menu")
execute "menu 550.5 &Latex.&".Compiler."<Tab>:TEX				:<C-U>TEX<CR>"
execute "cmenu 550.5 &Latex.&".Compiler."<Tab>:TEX				<C-U>TEX<CR>"
execute "imenu 550.5 &Latex.&".Compiler."<Tab>:TEX				<Esc>:TEX<CR>a"
function! <SID>TEXL_menuentry()
    let Compiler = get(g:CompilerMsg_Dict, matchstr(b:atp_TexCompiler, '^\s*\zs\S*'), 'Compile')
    if expand("%:p") != atplib#FullPath(b:atp_MainFile)
	execute "menu 550.6 Latex.".Compiler."\\ (subfile)<Tab>:TEXL			:<C-U>TEXL<CR>"
    else
	silent! execute "silent! unmenu Latex.".Compiler."\\ (subfile)"
    endif
endfunction
au BufEnter,BufWinEnter *.tex :call <SID>TEXL_menuentry()
execute "menu 550.7 &Latex.".Compiler."\\ debug<Tab>:TEX\\ debug		:<C-U>DTEX<CR>"
execute "cmenu 550.7 &Latex.".Compiler."\\ debug<Tab>:TEX\\ debug		<C-U>DTEX<CR>"
execute "imenu 550.7 &Latex.".Compiler."\\ debug<Tab>:TEX\\ debug		<Esc>:DTEX<CR>a"
execute "menu 550.8 &Latex.".Compiler."\\ &twice<Tab>:2TEX			:<C-U>2TEX<CR>"
execute "cmenu 550.8 &Latex.".Compiler."\\ &twice<Tab>:2TEX			<C-U>2TEX<CR>"
execute "imenu 550.8 &Latex.".Compiler."\\ &twice<Tab>:2TEX			<Esc>:2TEX<CR>a"
nmenu 550.9 &Latex.&MakeLatex<Tab>:MakeLatex					:<C-U>MakeLatex<CR>
cmenu 550.9 &Latex.&MakeLatex<Tab>:MakeLatex					<C-U>MakeLatex<CR>
imenu 550.9 &Latex.&MakeLatex<Tab>:MakeLatex					<Esc>:MakeLatex<CR>a
nmenu 550.10 &Latex.&Kill<Tab>:Kill						:<C-U>Kill<CR>
cmenu 550.10 &Latex.&Kill<Tab>:Kill						<C-U>Kill<CR>
imenu 550.10 &Latex.&Kill<Tab>:Kill						<Esc>:Kill<CR>a
menu 550.11 &Latex.&Bibtex<Tab>:Bibtex						:<C-U>Bibtex<CR>
cmenu 550.11 &Latex.&Bibtex<Tab>:Bibtex						<C-U>Bibtex<CR>
imenu 550.11 &Latex.&Bibtex<Tab>:Bibtex						<Esc>:Bibtex<CR>a
if Viewer != ""
    execute "menu 550.11 &Latex.&View\\ with\\ ".Viewer."<Tab>:ViewOutput 	:<C-U>ViewOutput<CR>"
    execute "cmenu 550.11 &Latex.&View\\ with\\ ".Viewer."<Tab>:ViewOutput 	<C-U>ViewOutput<CR>"
    execute "imenu 550.11 &Latex.&View\\ with\\ ".Viewer."<Tab>:ViewOutput 	<Esc>:ViewOutput<CR>a"
else
    execute "menu 550.11 &Latex.&View\\ Output<Tab>:ViewOutput	 		:<C-U>ViewOutput<CR>"
    execute "cmenu 550.11 &Latex.&View\\ Output<Tab>:ViewOutput	 		<C-U>ViewOutput<CR>"
    execute "imenu 550.11 &Latex.&View\\ Output<Tab>:ViewOutput 		<Esc>:ViewOutput<CR>a"
endif
"
menu 550.20.1 &Latex.&Errors<Tab>:ShowErrors					:<C-U>ShowErrors<CR>
cmenu 550.20.1 &Latex.&Errors<Tab>:ShowErrors					<C-U>ShowErrors<CR>
imenu 550.20.1 &Latex.&Errors<Tab>:ShowErrors					<Esc>:ShowErrors<CR>
menu 550.20.1 &Latex.&Log.&Open\ Log\ File<Tab>:ShowErrors\ o			:<C-U>ShowErrors\ o<CR>
cmenu 550.20.1 &Latex.&Log.&Open\ Log\ File<Tab>:ShowErrors\ o			<C-U>ShowErrors\ o<CR>
imenu 550.20.1 &Latex.&Log.&Open\ Log\ File<Tab>:ShowErrors\ o			<Esc>:ShowErrors\ o<CR>
if t:atp_DebugMode ==? "debug"
    menu 550.20.5 &Latex.&Log.Toggle\ &Debug\ Mode\ [on]			:<C-U>ToggleDebugMode<CR>
    cmenu 550.20.5 &Latex.&Log.Toggle\ &Debug\ Mode\ [on]			<C-U>ToggleDebugMode<CR>
    imenu 550.20.5 &Latex.&Log.Toggle\ &Debug\ Mode\ [on]			<Esc>:ToggleDebugMode<CR>a
else
    menu 550.20.5 &Latex.&Log.Toggle\ &Debug\ Mode\ [off]			:<C-U>ToggleDebugMode<CR>
    cmenu 550.20.5 &Latex.&Log.Toggle\ &Debug\ Mode\ [off]			<C-U>ToggleDebugMode<CR>
    imenu 550.20.5 &Latex.&Log.Toggle\ &Debug\ Mode\ [off]			<Esc>:ToggleDebugMode<CR>a
endif  
menu 550.20.20 &Latex.&Log.-ShowErrors-						:
menu 550.20.20 &Latex.&Log.&Warnings<Tab>:ShowErrors\ w 			:<C-U>ShowErrors w<CR>
cmenu 550.20.20 &Latex.&Log.&Warnings<Tab>:ShowErrors\ w 			<C-U>ShowErrors w<CR>
imenu 550.20.20 &Latex.&Log.&Warnings<Tab>:ShowErrors\ w 			<Esc>:ShowErrors w<CR>
menu 550.20.20 &Latex.&Log.&Citation\ Warnings<Tab>:ShowErrors\ c		:<C-U>ShowErrors c<CR>
cmenu 550.20.20 &Latex.&Log.&Citation\ Warnings<Tab>:ShowErrors\ c		<C-U>ShowErrors c<CR>
imenu 550.20.20 &Latex.&Log.&Citation\ Warnings<Tab>:ShowErrors\ c		<Esc>:ShowErrors c<CR>
menu 550.20.20 &Latex.&Log.&Reference\ Warnings<Tab>:ShowErrors\ r		:<C-U>ShowErrors r<CR>
cmenu 550.20.20 &Latex.&Log.&Reference\ Warnings<Tab>:ShowErrors\ r		<C-U>ShowErrors r<CR>
imenu 550.20.20 &Latex.&Log.&Reference\ Warnings<Tab>:ShowErrors\ r		<Esc>:ShowErrors r<CR>
menu 550.20.20 &Latex.&Log.&Font\ Warnings<Tab>ShowErrors\ f			:<C-U>ShowErrors f<CR>
cmenu 550.20.20 &Latex.&Log.&Font\ Warnings<Tab>ShowErrors\ f			<C-U>ShowErrors f<CR>
imenu 550.20.20 &Latex.&Log.&Font\ Warnings<Tab>ShowErrors\ f			<Esc>:ShowErrors f<CR>
menu 550.20.20 &Latex.&Log.Font\ Warnings\ &&\ Info<Tab>:ShowErrors\ fi		:<C-U>ShowErrors fi<CR>
cmenu 550.20.20 &Latex.&Log.Font\ Warnings\ &&\ Info<Tab>:ShowErrors\ fi	<C-U>ShowErrors fi<CR>
imenu 550.20.20 &Latex.&Log.Font\ Warnings\ &&\ Info<Tab>:ShowErrors\ fi	<Esc>:ShowErrors fi<CR>
menu 550.20.20 &Latex.&Log.&Show\ Files<Tab>:ShowErrors\ F			:<C-U>ShowErrors F<CR>
cmenu 550.20.20 &Latex.&Log.&Show\ Files<Tab>:ShowErrors\ F			<C-U>ShowErrors F<CR>
imenu 550.20.20 &Latex.&Log.&Show\ Files<Tab>:ShowErrors\ F			<Esc>:ShowErrors F<CR>
"
menu 550.20.20 &Latex.&Log.-PdfFotns- 						:
menu 550.20.20 &Latex.&Log.&Pdf\ Fonts<Tab>:PdfFonts				:<C-U>PdfFonts<CR>
cmenu 550.20.20 &Latex.&Log.&Pdf\ Fonts<Tab>:PdfFonts				<C-U>PdfFonts<CR>
imenu 550.20.20 &Latex.&Log.&Pdf\ Fonts<Tab>:PdfFonts				<Esc>:PdfFonts<CR>

menu 550.20.20 &Latex.&Log.-Delete-						:
menu 550.20.20 &Latex.&Log.&Delete\ Tex\ Output\ Files<Tab>:Delete		:<C-U>Delete<CR>
cmenu 550.20.20 &Latex.&Log.&Delete\ Tex\ Output\ Files<Tab>:Delete		<C-U>Delete<CR>
imenu 550.20.20 &Latex.&Log.&Delete\ Tex\ Output\ Files<Tab>:Delete		<Esc>:Delete<CR>
menu 550.20.20 &Latex.&Log.Set\ Error\ File<Tab>:SetErrorFile			:<C-U>SetErrorFile<CR> 
cmenu 550.20.20 &Latex.&Log.Set\ Error\ File<Tab>:SetErrorFile			<C-U>SetErrorFile<CR> 
imenu 550.20.20 &Latex.&Log.Set\ Error\ File<Tab>:SetErrorFile			<Esc>:SetErrorFile<CR>a
"
menu 550.25 &Latex.-Print- 							:
menu 550.26 &Latex.&SshPrint<Tab>:SshPrint					:<C-U>SshPrint 
cmenu 550.26 &Latex.&SshPrint<Tab>:SshPrint					<C-U>SshPrint 
imenu 550.26 &Latex.&SshPrint<Tab>:SshPrint					<Esc>:SshPrinta
"
menu 550.30 &Latex.-TOC- 							:
menu 550.30 &Latex.&Table\ of\ Contents<Tab>:TOC				:<C-U>TOC<CR>
cmenu 550.30 &Latex.&Table\ of\ Contents<Tab>:TOC				<C-U>TOC<CR>
imenu 550.30 &Latex.&Table\ of\ Contents<Tab>:TOC				<Esc>:TOC<CR>
menu 550.30 &Latex.L&abels<Tab>:Labels						:<C-U>Labels<CR>
cmenu 550.30 &Latex.L&abels<Tab>:Labels						<C-U>Labels<CR>
imenu 550.30 &Latex.L&abels<Tab>:Labels						<Esc>:Labels<CR>
if b:atp_LatexTags
    menu 550.30 &Latex.T&ags<Tab>:Tags						:<C-U>Tags<CR>
    cmenu 550.30 &Latex.T&ags<Tab>:Tags						<C-U>Tags<CR>
    imenu 550.30 &Latex.T&ags<Tab>:Tags						<Esc>:Tags<CR>
else
    menu 550.30 &Latex.T&ags<Tab>:LatexTags					:<C-U>LatexTags<CR>
    cmenu 550.30 &Latex.T&ags<Tab>:LatexTags					<C-U>LatexTags<CR>
    imenu 550.30 &Latex.T&ags<Tab>:LatexTags					<Esc>:LatexTags<CR>
endif
"
menu 550.40 &Latex.&Go\ to.&GotoFile<Tab>:GotoFile				:GotoFile<CR>
cmenu 550.40 &Latex.&Go\ to.&GotoFile<Tab>:GotoFile				GotoFile<CR>
imenu 550.40 &Latex.&Go\ to.&GotoFile<Tab>:GotoFile				<Esc>:GotoFile<CR>
menu 550.40 &Latex.&Go\ to.&GotoLabel<Tab>:GotoLabel				:GotoLabel<CR>
cmenu 550.40 &Latex.&Go\ to.&GotoLabel<Tab>:GotoLabel				GotoLabel<CR>
imenu 550.40 &Latex.&Go\ to.&GotoLabel<Tab>:GotoLabel				<Esc>:GotoLabel<CR>
menu 550.40 &Latex.&Go\ to.&GotoNamedDest<Tab>(Xpdf\ only)			:GotoNamedDest 
cmenu 550.40 &Latex.&Go\ to.&GotoNamedDest<Tab>(Xpdf\ only)			GotoNamedDest 
imenu 550.40 &Latex.&Go\ to.&GotoNamedDest<Tab>(Xpdf\ only)			<Esc>:GotoNamedDest 
"
menu 550.40 &Latex.&Go\ to.-Environment- 					:
menu 550.40 &Latex.&Go\ to.Next\ Definition<Tab>:F\ definition			:<C-U>F definition<CR>
cmenu 550.40 &Latex.&Go\ to.Next\ Definition<Tab>:F\ definition			<C-U>F definition<CR>
imenu 550.40 &Latex.&Go\ to.Next\ Definition<Tab>:F\ definition			<Esc>:F definition<CR>
menu 550.40 &Latex.&Go\ to.Previuos\ Definition<Tab>:B\ definition		:<C-U>B definition<CR>
cmenu 550.40 &Latex.&Go\ to.Previuos\ Definition<Tab>:B\ definition		<C-U>B definition<CR>
imenu 550.40 &Latex.&Go\ to.Previuos\ Definition<Tab>:B\ definition		<Esc>:B definition<CR>
menu 550.40 &Latex.&Go\ to.Next\ Environment<Tab>:F\ [pattern]			:<C-U>B
cmenu 550.40 &Latex.&Go\ to.Next\ Environment<Tab>:F\ [pattern]			<C-U>B
imenu 550.40 &Latex.&Go\ to.Next\ Environment<Tab>:F\ [pattern]			<Esc>:B
menu 550.40 &Latex.&Go\ to.Previuos\ Environment<Tab>:B\ [pattern]		:<C-U>B
cmenu 550.40 &Latex.&Go\ to.Previuos\ Environment<Tab>:B\ [pattern]		<C-U>B
imenu 550.40 &Latex.&Go\ to.Previuos\ Environment<Tab>:B\ [pattern]		<Esc>:B
"
menu 550.40 &Latex.&Go\ to.-Section- 						:
menu 550.40 &Latex.&Go\ to.&Next\ Section<Tab>:NSec				:NSec<CR>
cmenu 550.40 &Latex.&Go\ to.&Next\ Section<Tab>:NSec				NSec<CR>
imenu 550.40 &Latex.&Go\ to.&Next\ Section<Tab>:NSec				<Esc>:NSec<CR>
menu 550.40 &Latex.&Go\ to.&Previuos\ Section<Tab>:PSec				:<C-U>PSec<CR>
cmenu 550.40 &Latex.&Go\ to.&Previuos\ Section<Tab>:PSec			<C-U>PSec<CR>
imenu 550.40 &Latex.&Go\ to.&Previuos\ Section<Tab>:PSec			<Esc>:PSec<CR>
menu 550.40 &Latex.&Go\ to.Next\ Chapter<Tab>:NChap				:<C-U>NChap<CR>
cmenu 550.40 &Latex.&Go\ to.Next\ Chapter<Tab>:NChap				<C-U>NChap<CR>
imenu 550.40 &Latex.&Go\ to.Next\ Chapter<Tab>:NChap				<Esc>:NChap<CR>
menu 550.40 &Latex.&Go\ to.Previous\ Chapter<Tab>:PChap				:<C-U>PChap<CR>
cmenu 550.40 &Latex.&Go\ to.Previous\ Chapter<Tab>:PChap			<C-U>PChap<CR>
imenu 550.40 &Latex.&Go\ to.Previous\ Chapter<Tab>:PChap			<Esc>:PChap<CR>
menu 550.40 &Latex.&Go\ to.Next\ Part<Tab>:NPart				:<C-U>NPart<CR>
cmenu 550.40 &Latex.&Go\ to.Next\ Part<Tab>:NPart				<C-U>NPart<CR>
imenu 550.40 &Latex.&Go\ to.Next\ Part<Tab>:NPart				<Esc>:NPart<CR>
menu 550.40 &Latex.&Go\ to.Previuos\ Part<Tab>:PPart				:<C-U>PPart<CR>
cmenu 550.40 &Latex.&Go\ to.Previuos\ Part<Tab>:PPart				<C-U>PPart<CR>
imenu 550.40 &Latex.&Go\ to.Previuos\ Part<Tab>:PPart				<Esc>:PPart<CR>
"
menu 550.50 &Latex.-Bib-							:
menu 550.50 &Latex.Bib\ Search<Tab>:Bibsearch\ [pattern]			:<C-U>BibSearch 
cmenu 550.50 &Latex.Bib\ Search<Tab>:Bibsearch\ [pattern]			<C-U>BibSearch 
imenu 550.50 &Latex.Bib\ Search<Tab>:Bibsearch\ [pattern]			<Esc>:BibSearch 
menu 550.50 &Latex.Input\ Files<Tab>:InputFiles					:<C-U>InputFiles<CR>
cmenu 550.50 &Latex.Input\ Files<Tab>:InputFiles				<C-U>InputFiles<CR>
imenu 550.50 &Latex.Input\ Files<Tab>:InputFiles				<Esc>:InputFiles<CR>
"
menu 550.60 &Latex.-Viewer-							:
menu 550.60 &Latex.Set\ &XPdf\ (forward\ search)<Tab>:SetXpdf			:<C-U>SetXpdf<CR>
cmenu 550.60 &Latex.Set\ &XPdf\ (forward\ search)<Tab>:SetXpdf			<C-U>SetXpdf<CR>
imenu 550.60 &Latex.Set\ &XPdf\ (forward\ search)<Tab>:SetXpdf			<Esc>:SetXpdf<CR>
menu 550.60 &Latex.Set\ &Okular\ (forward\/reverse\ search)<Tab>:SetOkular	:<C-U>SetOkular<CR>
cmenu 550.60 &Latex.Set\ &Okular\ (forward\/reverse\ search)<Tab>:SetOkular	<C-U>SetOkular<CR>
imenu 550.60 &Latex.Set\ &Okular\ (forward\/reverse\ search)<Tab>:SetOkular	<Esc>:SetOkular<CR>
menu 550.60 &Latex.Set\ X&Dvi\ (forward\/reverse\ search)<Tab>:SetXdvi		:<C-U>SetXdvi<CR>
cmenu 550.60 &Latex.Set\ X&Dvi\ (forward\/reverse\ search)<Tab>:SetXdvi		<C-U>SetXdvi<CR>
imenu 550.60 &Latex.Set\ X&Dvi\ (forward\/reverse\ search)<Tab>:SetXdvi		<Esc>:SetXdvi<CR>
"
menu 550.70 &Latex.-Editting-							:
"
" ToDo: show options doesn't work from the menu (it disappears immediately, but at
" some point I might change it completely)
menu 550.70 &Latex.&Options.&Show\ Options<Tab>:ShowOptions[!]			:<C-U>ShowOptions 
cmenu 550.70 &Latex.&Options.&Show\ Options<Tab>:ShowOptions[!]			<C-U>ShowOptions 
imenu 550.70 &Latex.&Options.&Show\ Options<Tab>:ShowOptions[!]			<Esc>:ShowOptions 
if g:atp_callback
    menu 550.70 &Latex.&Options.Toggle\ &Call\ Back\ [on]<Tab>g:atp_callback	:<C-U>ToggleCallBack<CR>
    cmenu 550.70 &Latex.&Options.Toggle\ &Call\ Back\ [on]<Tab>g:atp_callback	<C-U>ToggleCallBack<CR>
    imenu 550.70 &Latex.&Options.Toggle\ &Call\ Back\ [on]<Tab>g:atp_callback	<Esc>:ToggleCallBack<CR>a
else
    menu 550.70 &Latex.&Options.Toggle\ &Call\ Back\ [off]<Tab>g:atp_callback	:<C-U>ToggleCallBack<CR>
    cmenu 550.70 &Latex.&Options.Toggle\ &Call\ Back\ [off]<Tab>g:atp_callback	<C-U>ToggleCallBack<CR>
    imenu 550.70 &Latex.&Options.Toggle\ &Call\ Back\ [off]<Tab>g:atp_callback	<Esc>:ToggleCallBack<CR>a
endif  
menu 550.70 &Latex.&Options.-set\ options- 					:
" There is menu for ToggleAuTeX
" menu 550.70 &Latex.&Options.Automatic\ TeX\ Processing<Tab>b:atp_autex		:<C-U>let b:atp_autex=
" imenu 550.70 &Latex.&Options.Automatic\ TeX\ Processing<Tab>b:atp_autex		<Esc>:let b:atp_autex=
menu 550.70 &Latex.&Options.Set\ TeX\ Compiler<Tab>:Compiler			:<C-U>Compiler 
cmenu 550.70 &Latex.&Options.Set\ TeX\ Compiler<Tab>:Compiler			<C-U>Compiler 
imenu 550.70 &Latex.&Options.Set\ TeX\ Compiler<Tab>:Compiler			<Esc>:Compiler 
menu 550.70 &Latex.&Options.Set\ Debug\ Mode<Tab>:DebugMode\ {mode}		:<C-U>DebugMode
cmenu 550.70 &Latex.&Options.Set\ Debug\ Mode<Tab>:DebugMode\ {mode}		<C-U>DebugMode
imenu 550.70 &Latex.&Options.Set\ Debug\ Mode<Tab>:Compiler\ {compiler}		<Esc>:DebugMode 
menu 550.70 &Latex.&Options.Set\ Runs<Tab>b:atp_auruns				:<C-U>let b:atp_auruns=
cmenu 550.70 &Latex.&Options.Set\ Runs<Tab>b:atp_auruns				<C-U>let b:atp_auruns=
imenu 550.70 &Latex.&Options.Set\ Runs<Tab>b:atp_auruns				<Esc>:let b:atp_auruns=
menu 550.70 &Latex.&Options.Set\ Viewer<Tab>:Viewer\ {viewer}			:<C-U>Viewer 
cmenu 550.70 &Latex.&Options.Set\ Viewer<Tab>:Viewer\ {viewer}			<C-U>Viewer 
imenu 550.70 &Latex.&Options.Set\ Viewer<Tab>:Viewer\ {viewer}			<Esc>:Viewer 
menu 550.70 &Latex.&Options.Set\ Output\ Directory<Tab>b:atp_OutDir		:<C-U>let b:atp_OutDir="
cmenu 550.70 &Latex.&Options.Set\ Output\ Directory<Tab>b:atp_OutDir		<C-U>let b:atp_OutDir="
imenu 550.70 &Latex.&Options.Set\ Output\ Directory<Tab>b:atp_OutDir		<Esc>:let b:atp_OutDir="
menu 550.70 &Latex.&Options.Set\ Viewer\ Options				:<C-U>let b:atp_{matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')}Options=
cmenu 550.70 &Latex.&Options.Set\ Viewer\ Options 				<C-U>let b:atp_{matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')}Options=
imenu 550.70 &Latex.&Options.Set\ Viewer\ Options				<Esc>:let b:atp_{matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')}Options=
menu 550.70 &Latex.&Options.Set\ Output\ Directory\ to\ the\ default\ value<Tab>:SetOutDir	:<C-U>SetOutDir<CR> 
cmenu 550.70 &Latex.&Options.Set\ Output\ Directory\ to\ the\ default\ value<Tab>:SetOutDir	<C-U>SetOutDir<CR> 
imenu 550.70 &Latex.&Options.Set\ Output\ Directory\ to\ the\ default\ value<Tab>:SetOutDir	<Esc>:SetOutDir<CR> 
" The title is misleading! I think it is not needed here.
" menu 550.70 &Latex.&Options.Ask\ for\ the\ Output\ Directory<Tab>g:askfortheoutdir		:<C-U>let g:askfortheoutdir="
" imenu 550.70 &Latex.&Options.Ask\ for\ the\ Output\ Directory<Tab>g:askfortheoutdir		<Esc>:let g:askfortheoutdir="
menu 550.70 &Latex.&Options.Set\ Error\ File<Tab>:SetErrorFile			:<C-U>SetErrorFile<CR> 
cmenu 550.70 &Latex.&Options.Set\ Error\ File<Tab>:SetErrorFile			<C-U>SetErrorFile<CR> 
imenu 550.70 &Latex.&Options.Set\ Error\ File<Tab>:SetErrorFile			<Esc>:SetErrorFile<CR> 
menu 550.70 &Latex.&Options.Which\ TeX\ files\ to\ copy<Tab>g:atp_keep		:<C-U>let g:atp_keep="
cmenu 550.70 &Latex.&Options.Which\ TeX\ files\ to\ copy<Tab>g:atp_keep		<C-U>let g:atp_keep="
imenu 550.70 &Latex.&Options.Which\ TeX\ files\ to\ copy<Tab>g:atp_keep		<Esc>:let g:atp_keep="
menu 550.70 &Latex.&Options.Tex\ extensions<Tab>g:atp_tex_extensions		:<C-U>let g:atp_tex_extensions="
cmenu 550.70 &Latex.&Options.Tex\ extensions<Tab>g:atp_tex_extensions		<C-U>let g:atp_tex_extensions="
imenu 550.70 &Latex.&Options.Tex\ extensions<Tab>g:atp_tex_extensions		<Esc>:let g:atp_tex_extensions="
menu 550.70 &Latex.&Options.Default\ Bib\ Flags<Tab>g:defaultbibflags		:<C-U>let g:defaultbibflags="
cmenu 550.70 &Latex.&Options.Default\ Bib\ Flags<Tab>g:defaultbibflags		<C-U>let g:defaultbibflags="
imenu 550.70 &Latex.&Options.Default\ Bib\ Flags<Tab>g:defaultbibflags		<Esc>:let g:defaultbibflags="
"
if b:atp_autex
    menu 550.75 &Latex.&Toggle\ AuTeX\ [on]<Tab>b:atp_autex	:<C-U>ToggleAuTeX<CR>
    cmenu 550.75 &Latex.&Toggle\ AuTeX\ [on]<Tab>b:atp_autex	<C-U>ToggleAuTeX<CR>
    imenu 550.75 &Latex.&Toggle\ AuTeX\ [on]<Tab>b:atp_autex	<ESC>:ToggleAuTeX<CR>a
else
    menu 550.75 &Latex.&Toggle\ AuTeX\ [off]<Tab>b:atp_autex	:<C-U>ToggleAuTeX<CR>
    cmenu 550.75 &Latex.&Toggle\ AuTeX\ [off]<Tab>b:atp_autex	<C-U>ToggleAuTeX<CR>
    imenu 550.75 &Latex.&Toggle\ AuTeX\ [off]<Tab>b:atp_autex	<ESC>:ToggleAuTeX<CR>a
endif
menu 550.78 &Latex.&Toggle\ Space\ [off]<Tab>cmap\ <space>\ \\_s\\+ 		:<C-U>ToggleSpace<CR>
cmenu 550.78 &Latex.&Toggle\ Space\ [off]<Tab>cmap\ <space>\ \\_s\\+ 		<C-U>ToggleSpace<CR>
imenu 550.78 &Latex.&Toggle\ Space\ [off]<Tab>cmap\ <space>\ \\_s\\+ 		<Esc>:ToggleSpace<CR>a
tmenu &Latex.&Toggle\ Space\ [off] cmap <space> \_s\+ is curently off
" ToggleNn menu is made by s:LoadHistory
if g:atp_mapNn
    menu 550.79 &Latex.Toggle\ &Nn\ [on]<Tab>:ToggleNn				:<C-U>ToggleNn<CR>
    cmenu 550.79 &Latex.Toggle\ &Nn\ [on]<Tab>:ToggleNn				<C-U>ToggleNn<CR>
    imenu 550.79 &Latex.Toggle\ &Nn\ [on]<Tab>:ToggleNn				<Esc>:ToggleNn<CR>a
    tmenu Latex.Toggle\ Nn\ [on] n,N vim normal commands.
else
    menu 550.79 &Latex.Toggle\ &Nn\ [off]<Tab>:ToggleNn				:<C-U>ToggleNn<CR>
    cmenu 550.79 &Latex.Toggle\ &Nn\ [off]<Tab>:ToggleNn				<C-U>ToggleNn<CR>
    imenu 550.79 &Latex.Toggle\ &Nn\ [off]<Tab>:ToggleNn			<Esc>:ToggleNn<CR>a
    tmenu Latex.Toggle\ Nn\ [off] atp maps to n,N.
endif
if g:atp_MathOpened
    menu 550.80 &Latex.Toggle\ &Check\ if\ in\ Math\ [on]<Tab>g:atp_MathOpened   :<C-U>ToggleCheckMathOpened<CR>
    cmenu 550.80 &Latex.Toggle\ &Check\ if\ in\ Math\ [on]<Tab>g:atp_MathOpened   <C-U>ToggleCheckMathOpened<CR>
    imenu 550.80 &Latex.Toggle\ &Check\ if\ in\ Math\ [on]<Tab>g:atp_MathOpened  <Esc>:ToggleCheckMathOpened<CR>a
else
    menu 550.80 &Latex.Toggle\ &Check\ if\ in\ Math\ [off]<Tab>g:atp_MathOpened  :<C-U>ToggleCheckMathOpened<CR>
    cmenu 550.80 &Latex.Toggle\ &Check\ if\ in\ Math\ [off]<Tab>g:atp_MathOpened  <C-U>ToggleCheckMathOpened<CR>
    imenu 550.80 &Latex.Toggle\ &Check\ if\ in\ Math\ [off]<Tab>g:atp_MathOpened <Esc>:ToggleCheckMathOpened<CR>a
endif
endif

" vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1
ftplugin/ATP_files/motion.vim	[[[1
285
" Author:	Marcin Szamotulski
" Description:	This file contains motion and highlight functions of ATP.
" Note:		This file is a part of Automatic Tex Plugin for Vim.
" Language:	tex
" Last Change:

let s:sourced = ( !exists("s:sourced") ? 0 : 1 )

" CTOC Function:
" {{{1 CTOC
function! CTOC(...)

    if &l:filetype !~ 'tex$' || expand("%:e") != 'tex'
	return ""
    endif

    let winsavedview = winsaveview()
    try
	if exists("b:atp_MainFile") && bufloaded(atplib#FullPath(b:atp_MainFile))
	    let file = getbufline(bufnr(atplib#FullPath(b:atp_MainFile)), 0, "$")
	elseif exists("b:atp_MainFile") && filereadable(atplib#FullPath(b:atp_MainFile))
	    let file = readfile(atplib#FullPath(b:atp_MainFile))
	else
	    let s:document_class = ""
	endif
	for fline in file
	    if fline =~# '^\([^%]\|\\%\)*\\documentclass\>'
		break
	    endif
	endfor
	let s:document_class = matchstr(fline, '\\documentclass\[.*\]{\s*\zs[^}]*\ze\s*}')
    catch /E\(484\|121\):/
	if !exists("s:document_class")
	    let s:document_class = ""
	endif
    endtry
    if s:document_class == "beamer"
	let saved_pos = getpos(".")
	if getline(line(".")) =~ '^\([^%]\|\\%\)*\\end\s*{\s*frame\s*}' 
	    call cursor(line(".")-1, len(getline(line("."))))
	endif
	keepjumps call searchpair('^\([^%]\|\\%\)*\\begin\s*{\s*frame\s*}', '', '^\([^%]\|\\%\)*\\end\s*{\s*frame\s*}', 'cbW', '',
		    \ search('^\([^%]\|\\%\)*\\begin\s*{\s*frame\s*}', 'bnW'))
	let limit 	= search('^\([^%]\|\\%\)*\\end\s*{\s*frame\s*}', 'nW')
	let pos	= [ line("."), col(".") ]
	keepjumps call search('^\([^%]\|\\%\)*\frametitle\>\zs{', 'W', limit)
	if pos != getpos(".")[1:2]
	    let a 	= @a
	    if mode() ==# 'n'
		" We can't use this normal mode command in visual mode.
		keepjumps normal! "ayi}
		let title	= substitute(@a, '\_s\+', ' ', 'g')
		let @a 	= a
	    else
		let title	= matchstr(getline(line(".")), '\\frametitle\s*{\s*\zs[^}]*\ze\(}\|$\)')
		let title	= substitute(title, '\s\+', ' ', 'g')
		let title	= substitute(title, '\s\+$', '', 'g')
		if getline(line(".")) =~ '\\frametitle\s*{[^}]*$'
		    let title 	.= " ".matchstr(getline(line(".")+1), '\s*\zs[^}]*\ze\(}\|$\)')
		endif
	    endif
	    call winrestview(winsavedview)
	    return substitute(strpart(title,0,b:atp_TruncateStatusSection/2), '\_s*$', '','')
	else
	    call cursor(saved_pos[1:2])
	    return ""
	endif
    endif

    let names		= atplib#motion#ctoc()
    let chapter_name	= get(names, 0, '')
    let section_name	= get(names, 1, '')
    let subsection_name	= get(names, 2, '')


    if chapter_name == "" && section_name == "" && subsection_name == ""

	if a:0 != 0
	    return ""
	else
	    echo "" 
	endif
	
    elseif chapter_name != ""
	if section_name != ""
	    if a:0 != 0
		return substitute(strpart(chapter_name,0,b:atp_TruncateStatusSection/2), '\_s*$', '','') . "/" . substitute(strpart(section_name,0,b:atp_TruncateStatusSection/2), '\_s*$', '','')
	    endif
	else
	    if a:0 != 0
		return substitute(strpart(chapter_name,0,b:atp_TruncateStatusSection), '\_s*$', '','')
	    endif
	endif
    elseif chapter_name == "" && section_name != ""
	if subsection_name != ""
	    if a:0 != 0
		return substitute(strpart(section_name,0,b:atp_TruncateStatusSection/2), '\_s*$', '','') . "/" . substitute(strpart(subsection_name,0,b:atp_TruncateStatusSection/2), '\_s*$', '','')
	    endif
	else
	    if a:0 != 0
		return substitute(strpart(section_name,0,b:atp_TruncateStatusSection), '\_s*$', '','')
	    endif
	endif
    elseif chapter_name == "" && section_name == "" && subsection_name != ""
	if a:0 != 0
	    return substitute(strpart(subsection_name,0,b:atp_TruncateStatusSection), '\_s*$', '','')
	endif
    endif
endfunction "}}}1

" AutoCommands:
" {{{
augroup ATP_BufList
    " Add opened files to t:atp_toc_buflist.
    au!
    au BufEnter *.tex call atplib#motion#buflist()
augroup END
function! <SID>toc_onwrite()
    if g:atp_python_toc
	" check if there is a __ToC__ window:
	if index(map(tabpagebuflist(), 'bufname(v:val)'), "__ToC__") != -1
	    TOC!
	    let ei=&ei
	    set ei=all
	    wincmd w
	    let &ei=ei
	endif
    endif
endfunction
augroup ATP_TOC_onwrite
    au!
    au BufWritePost *.tex call <SID>toc_onwrite()
augroup END
" }}}

" Commands And Maps:
" {{{1
if exists(":Tags") != 2
    let b:atp_LatexTags = 1
    command! -buffer -bang Tags						:call atplib#motion#LatexTags(<q-bang>)
else
    let b:atp_LatexTags = 0
    command! -buffer -bang LatexTags					:call atplib#motion#LatexTags(<q-bang>)
endif
command! -nargs=? -complete=custom,atplib#motion#RemoveFromToCComp RemoveFromToC	:call atplib#motion#RemoveFromToC(<q-args>)
map	<buffer> <silent> <Plug>JumptoPreviousEnvironment		:call atplib#motion#JumptoEnvironment(1)<CR>
map	<buffer> <silent> <Plug>JumptoNextEnvironment			:call atplib#motion#JumptoEnvironment(0)<CR>
command! -buffer -count=1 Part		:call atplib#motion#ggGotoSection(<q-count>, 'part')
command! -buffer -count=1 Chap		:call atplib#motion#ggGotoSection(<q-count>, 'chapter')
command! -buffer -count=1 Sec		:call atplib#motion#ggGotoSection(<q-count>, 'section')
command! -buffer -count=1 SSec		:call atplib#motion#ggGotoSection(<q-count>, 'subsection')

command! -buffer -nargs=1 -complete=custom,atplib#motion#CompleteDestinations GotoNamedDest	:call atplib#motion#GotoNamedDestination(<f-args>)
command! -buffer -count=1 SkipCommentForward  	:call atplib#motion#SkipComment('fs', 'n', v:count1)
command! -buffer -count=1 SkipCommentBackward 	:call atplib#motion#SkipComment('bs', 'n', v:count1)
vmap <buffer> <Plug>SkipCommentForward	:call atplib#motion#SkipComment('fs', 'v', v:count1)<CR>
vmap <buffer> <Plug>SkipCommentBackward	:call atplib#motion#SkipComment('bs', 'v', , v:count1, col("."))<CR>

imap <Plug>TexSyntaxMotionForward	<Esc>:call atplib#motion#TexSyntaxMotion(1,1,1)<CR>a
imap <Plug>TexSyntaxMotionBackward	<Esc>:call atplib#motion#TexSyntaxMotion(0,1,1)<CR>a
nmap <Plug>TexSyntaxMotionForward	:call atplib#motion#TexSyntaxMotion(1,1)<CR>
nmap <Plug>TexSyntaxMotionBackward	:call atplib#motion#TexSyntaxMotion(0,1)<CR>

imap <Plug>TexJMotionForward	<Esc><Right>:call atplib#motion#JMotion('')<CR>i
imap <Plug>TexJMotionBackward	<Esc>:call atplib#motion#JMotion('b')<CR>a
nmap <Plug>TexJMotionForward	:call atplib#motion#JMotion('')<CR>
nmap <Plug>TexJMotionBackward	:call atplib#motion#JMotion('b')<CR>

" command! -buffer -nargs=1 -complete=buffer MakeToc	:echo atplib#motion#maketoc(fnamemodify(<f-args>, ":p"))[fnamemodify(<f-args>, ":p")] 
command! -buffer -bang -nargs=? TOC	:call atplib#motion#TOC(<q-bang>)
command! -buffer CTOC			:call CTOC()
command! -buffer -bang Labels		:call atplib#motion#Labels(<q-bang>)
command! -buffer -count=1 -nargs=? -complete=customlist,EnvCompletionWithoutStarEnvs Nenv	:call atplib#motion#GotoEnvironment('sW',<q-count>,<q-args>)  | let v:searchforward=1 
command! -buffer -count=1 -nargs=? -complete=customlist,EnvCompletionWithoutStarEnvs Penv	:call atplib#motion#GotoEnvironment('bsW',<q-count>,<q-args>) | let v:searchforward=0
"TODO: These two commands should also work with sections.
command! -buffer -count=1 -nargs=? -complete=custom,atplib#various#F_compl F	:call atplib#motion#GotoEnvironment('sW',<q-count>,<q-args>)  | let v:searchforward=1
command! -buffer -count=1 -nargs=? -complete=custom,atplib#various#F_compl B	:call atplib#motion#GotoEnvironment('bsW',<q-count>,<q-args>) | let v:searchforward=0

nnoremap <silent> <buffer> <Plug>GotoNextEnvironment		:<C-U>call atplib#motion#GotoEnvironment('sW',v:count1,'')<CR>
nnoremap <silent> <buffer> <Plug>GotoPreviousEnvironment	:<C-U>call atplib#motion#GotoEnvironment('bsW',v:count1,'')<CR>

nnoremap <silent> <buffer> <Plug>GotoNextMath			:<C-U>call atplib#motion#GotoEnvironment('sW',v:count1,'math')<CR>
nnoremap <silent> <buffer> <Plug>GotoPreviousMath		:<C-U>call atplib#motion#GotoEnvironment('bsW',v:count1,'math')<CR>

nnoremap <silent> <buffer> <Plug>GotoNextInlineMath		:<C-U>call atplib#motion#GotoEnvironment('sW',v:count1,'inlinemath')<CR>
nnoremap <silent> <buffer> <Plug>GotoPreviousInlineMath		:<C-U>call atplib#motion#GotoEnvironment('bsW',v:count1,'inlinemath')<CR>

nnoremap <silent> <buffer> <Plug>GotoNextDisplayedMath	 	:<C-U>call atplib#motion#GotoEnvironment('sW',v:count1,'displayedmath')<CR>
nnoremap <silent> <buffer> <Plug>GotoPreviousDisplayedMath	:<C-U>call atplib#motion#GotoEnvironment('bsW',v:count1,'displayedmath')<CR>

if &l:cpoptions =~# 'B'
    nnoremap <silent> <Plug>GotoNextSubSection		:<C-U>call atplib#motion#GotoSection("", v:count1, "s", "\\\\\\%(subsection\\\\|section\\\\|chapter\\\\|part\\)\\*\\=\\>", ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', '')<CR>
    onoremap <silent> <Plug>GotoNextSubSection		:<C-U>call atplib#motion#GotoSection("", v:count1, "s","\\\\\\%(subsection\\\\|section\\\\|chapter\\\\|part\\)\\*\\=\\>", 'vim')<CR>
    vnoremap <silent> <Plug>vGotoNextSubSection		m':<C-U>exe "normal! gv"<Bar>exe "normal! w"<Bar>call search('^\([^%]\\|\\\@<!\\%\)*\\\%(subsection\\|section\\|chapter\\|part\)\*\=\>\\|\\end\s*{\s*document\s*}', 'W')<Bar>exe "normal! b"<CR>

    nnoremap <silent> <Plug>GotoNextSection		:<C-U>call atplib#motion#GotoSection("", v:count1, "s", "\\\\\\%(section\\\\|chapter\\\\|part\\)\\*\\=\\>", ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', '')<CR>
    onoremap <silent> <Plug>GotoNextSection		:<C-U>call atplib#motion#GotoSection("", v:count1, "s", "\\\\\\%(section\\\\|chapter\\\\|part\\)\\*\\=\\>", 'vim')<CR>
    vnoremap <silent> <Plug>vGotoNextSection		m':<C-U>exe "normal! gv"<Bar>exe "normal! w"<Bar>call search('^\([^%]\\|\\\@<!\\%\)*\\\%(section\\|chapter\\|part\)\*\=\>\\|\\end\s*{\s*document\s*}', 'W')<Bar>exe "normal! b"<CR>

    nnoremap <silent> <Plug>GotoNextChapter		:<C-U>call atplib#motion#GotoSection("", v:count1, "s", "\\\\\\%(chapter\\\\|part\\)\\*\\=\\>", ( g:atp_mapNn ? 'atp' : 'vim' ))<CR>
    onoremap <silent> <Plug>GotoNextChapter		:<C-U>call atplib#motion#GotoSection("", v:count1, "s", "\\\\\\%(chapter\\\\|part\\)\\*\\=\\>", 'vim')<CR>
    vnoremap <silent> <Plug>vGotoNextChapter		m':<C-U>exe "normal! gv"<Bar>exe "normal! w"<Bar>call search('^\([^%]\\|\\\@<!\\%\)*\\\%(chapter\\|part\)\*\=\>\\|\\end\s*{\s*document\s*}', 'W')<Bar>exe "normal! b"<CR>

    nnoremap <silent> <Plug>GotoNextPart		:<C-U>call atplib#motion#GotoSection("", v:count1, "s", "\\\\part\\*\\=\\>", ( g:atp_mapNn ? 'atp' : 'vim' ), 'n')<CR>
    onoremap <silent> <Plug>GotoNextPart		:<C-U>call atplib#motion#GotoSection("", v:count1, "s", "\\\\part\\*\\=\\>", 'vim', 'n')<CR>
    vnoremap <silent> <Plug>vGotoNextPart		m':<C-U>exe "normal! gv"<Bar>exe "normal! w"<Bar>call search('^\([^%]\\|\\\@<!\\%\)*\\\%(part\*\=\>\\|\\end\s*{\s*document\s*}\)', 'W')<Bar>exe "normal! b"<CR>
else
    nnoremap <silent> <Plug>GotoNextSubSection		:<C-U>call atplib#motion#GotoSection("", v:count1, "s", '\\\\\\%(subsection\\\\|section\\\\|chapter\\\\|part\\)\\*\\=\\>', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', '')<CR>
    onoremap <silent> <Plug>GotoNextSubSection		:<C-U>call atplib#motion#GotoSection("", v:count1, "s",'\\\\\\%(subsection\\\\|section\\\\|chapter\\\\|part\\)\\*\\=\\>', 'vim')<CR>
    vnoremap <silent> <Plug>vGotoNextSubSection		m':<C-U>exe "normal! gv"<Bar>exe "normal! w"<Bar>call search('^\\([^%]\\\\|\\\\\\@<!\\\\%\\)*\\\\\\%(subsection\\\\|section\\\\|chapter\\\\|part\\)\\*\\=\\>\\\\|\\\\end\\s*{\\s*document\\s*}', 'W')<Bar>exe "normal! b"<CR>

    nnoremap <silent> <Plug>GotoNextSection		:<C-U>call atplib#motion#GotoSection("", v:count1, "s", '\\\\\\%(section\\\\|chapter\\\\|part\\)\\*\\=\\>', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', '')<CR>
    onoremap <silent> <Plug>GotoNextSection		:<C-U>call atplib#motion#GotoSection("", v:count1, "s", '\\\\\\%(section\\\\|chapter\\\\|part\\)\\*\\=\\>', 'vim')<CR>
    vnoremap <silent> <Plug>vGotoNextSection		m':<C-U>exe "normal! gv"<Bar>exe "normal! w"<Bar>call search('^\\([^%]\\\\|\\\\\\@<!\\\\%\\)*\\\\\\%(section\\\\|chapter\\\\|part\\)\\*\\=\\>\\\\|\\\\end\\s*{\\s*document\\s*}', 'W')<Bar>exe "normal! b"<CR>

    nnoremap <silent> <Plug>GotoNextChapter		:<C-U>call atplib#motion#GotoSection("", v:count1, "s", '\\\\\\%(chapter\\\\|part\\)\\*\\=\\>', ( g:atp_mapNn ? 'atp' : 'vim' ))<CR>
    onoremap <silent> <Plug>GotoNextChapter		:<C-U>call atplib#motion#GotoSection("", v:count1, "s", '\\\\\\%(chapter\\\\|part\\)\\*\\=\\>', 'vim')<CR>
    vnoremap <silent> <Plug>vGotoNextChapter		m':<C-U>exe "normal! gv"<Bar>exe "normal! w"<Bar>call search('^\\([^%]\\\\|\\\\\\@<!\\\\%\\)*\\\\\\%(chapter\\\\|part\\)\\*\\=\\>\\\\|\\\\end\\s*{\\s*document\\s*}', 'W')<Bar>exe "normal! b"<CR>

    nnoremap <silent> <Plug>GotoNextPart		:<C-U>call atplib#motion#GotoSection("", v:count1, "s", '\\\\part\\*\\=\\>', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n')<CR>
    onoremap <silent> <Plug>GotoNextPart		:<C-U>call atplib#motion#GotoSection("", v:count1, "s", '\\\\part\\*\\=\\>', 'vim', 'n')<CR>
    vnoremap <silent> <Plug>vGotoNextPart		m':<C-U>exe "normal! gv"<Bar>exe "normal! w"<Bar>call search('^\\([^%]\\\\|\\\\\\@<!\\\\%\\)*\\\\\\%(part\\*\\=\\>\\\\|\\\\end\\s*{\\s*document\\s*}\\)', 'W')<Bar>exe "normal! b"<CR>
endif

command! -buffer -bang -count=1 -nargs=? -complete=customlist,atplib#motion#Env_compl NSSSec		:call atplib#motion#GotoSection(<q-bang>, <q-count>, "s", '\\\%(subsubsection\|subsection\|section\|chapter\|part\)\*\=\>', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', <q-args>)
command! -buffer -bang -count=1 -nargs=? -complete=customlist,atplib#motion#Env_compl NSSec		:call atplib#motion#GotoSection(<q-bang>, <q-count>, "s", '\\\%(subsection\|section\|chapter\|part\)\*\=\>', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', <q-args>)
command! -buffer -bang -count=1 -nargs=? -complete=customlist,atplib#motion#Env_compl NSec		:call atplib#motion#GotoSection(<q-bang>, <q-count>, "s", '\\\%(section\|chapter\|part\)\*\=\>', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', <q-args>)
command! -buffer -bang -count=1 -nargs=? -complete=customlist,atplib#motion#Env_compl NChap		:call atplib#motion#GotoSection(<q-bang>, <q-count>, "s", '\\\%(chapter\|part\)\*\=\>', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', <q-args>)
command! -buffer -bang -count=1 -nargs=? -complete=customlist,atplib#motion#Env_compl NPart		:call atplib#motion#GotoSection(<q-bang>, <q-count>, "s", '\\part\*\=\>', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', <q-args>)

if &l:cpoptions =~# 'B'
    nnoremap <silent> <Plug>GotoPreviousSubSection	:<C-U>call atplib#motion#GotoSection("", v:count1, "sb", "\\\\\\%(subsection\\\\|section\\\\|chapter\\\\|part\\)\\*\\=\\>", ( g:atp_mapNn ? 'atp' : 'vim' ), 'n')<CR>
    onoremap <silent> <Plug>GotoPreviousSubSection	:<C-U>call atplib#motion#GotoSection("", v:count1, "sb", "\\\\\\%(subsection\\\\|section\\\\|chapter\\\\|part\\)\\*\\=\\>", 'vim')<CR>
    vnoremap <silent> <Plug>vGotoPreviousSubSection	m':<C-U>exe "normal! gv"<Bar>call search('\\\%(subsection\\|section\\|chapter\\|part\)\*\=\>\\|\\begin\s*{\s*document\s*}', 'bW')<CR>

    nnoremap <silent> <Plug>GotoPreviousSection	:<C-U>call atplib#motion#GotoSection("", v:count1, "sb", "\\\\\\%(section\\\\|chapter\\\\|part\\)\\*\\=\\>", ( g:atp_mapNn ? 'atp' : 'vim' ), 'n')<CR>
    onoremap <silent> <Plug>GotoPreviousSection	:<C-U>call atplib#motion#GotoSection("", v:count1, "sb", "\\\\\\%(section\\\\|chapter\\\\|part\\)\\*\\=\\>", 'vim')<CR>
    vnoremap <silent> <Plug>vGotoPreviousSection	m':<C-U>exe "normal! gv"<Bar>call search('\\\%(section\\|chapter\\|part\)\*\=\>\\|\\begin\s*{\s*document\s*}', 'bW')<CR>

    nnoremap <silent> <Plug>GotoPreviousChapter	:<C-U>call atplib#motion#GotoSection("", v:count1, "sb", "\\\\\\%(chapter\\\\|part\\)\\>", ( g:atp_mapNn ? 'atp' : 'vim' ))<CR>
    onoremap <silent> <Plug>GotoPreviousChapter	:<C-U>call atplib#motion#GotoSection("", v:count1, "sb", "\\\\\\%(chapter\\\\|part\\)\\>", 'vim')<CR
    vnoremap <silent> <Plug>vGotoPreviousChapter	m':<C-U>exe "normal! gv"<Bar>call search('\\\%(chapter\\|part\)\*\=\>\\|\\begin\s*{\s*document\s*}', 'bW')<CR>

    nnoremap <silent> <Plug>GotoPreviousPart	:<C-U>call atplib#motion#GotoSection("", v:count1, "sb", "\\\\part\\*\\=\\>", ( g:atp_mapNn ? 'atp' : 'vim' ))<CR>
    onoremap <silent> <Plug>GotoPreviousPart	:<C-U>call atplib#motion#GotoSection("", v:count1, "sb", "\\\\part\\*\\=\\>", 'vim')<CR>
    vnoremap <silent> <Plug>vGotoPreviousPart	m':<C-U>exe "normal! gv"<Bar>call search('\\\%(part\*\=\)\>', 'bW')<CR>
else
    nnoremap <silent> <Plug>GotoPreviousSubSection	:<C-U>call atplib#motion#GotoSection("", v:count1, "sb", '\\\\\\%(subsection\\\\|section\\\\|chapter\\\\|part\\)\\*\\=\\>', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n')<CR>
    onoremap <silent> <Plug>GotoPreviousSubSection	:<C-U>call atplib#motion#GotoSection("", v:count1, "sb", '\\\\\\%(subsection\\\\|section\\\\|chapter\\\\|part\\)\\*\\=\\>', 'vim')<CR>
    vnoremap <silent> <Plug>vGotoPreviousSubSection	m':<C-U>exe "normal! gv"<Bar>call search('\\\\\\%(subsection\\\\|section\\\\|chapter\\\\|part\\)\\*\\=\\>\\\\|\\\\begin\\s*{\\s*document\\s*}', 'bW')<CR>

    nnoremap <silent> <Plug>GotoPreviousSection	:<C-U>call atplib#motion#GotoSection("", v:count1, "sb", '\\\\\\%(section\\\\|chapter\\\\|part\\)\\*\\=\\>', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n')<CR>
    onoremap <silent> <Plug>GotoPreviousSection	:<C-U>call atplib#motion#GotoSection("", v:count1, "sb", '\\\\\\%(section\\\\|chapter\\\\|part\\)\\*\\=\\>', 'vim')<CR>
    vnoremap <silent> <Plug>vGotoPreviousSection	m':<C-U>exe "normal! gv"<Bar>call search('\\\\\\%(section\\\\|chapter\\\\|part\\)\\*\\=\\>\\\\|\\\\begin\\s*{\\s*document\\s*}', 'bW')<CR>

    nnoremap <silent> <Plug>GotoPreviousChapter	:<C-U>call atplib#motion#GotoSection("", v:count1, "sb", '\\\\\\%(chapter\\\\|part\\)\\>', ( g:atp_mapNn ? 'atp' : 'vim' ))<CR>
    onoremap <silent> <Plug>GotoPreviousChapter	:<C-U>call atplib#motion#GotoSection("", v:count1, "sb", '\\\\\\%(chapter\\\\|part\\)\\>', 'vim')<CR
    vnoremap <silent> <Plug>vGotoPreviousChapter	m':<C-U>exe "normal! gv"<Bar>call search('\\\\\\%(chapter\\\\|part\\)\\*\\=\\>\\\\|\\\\begin\\s*{\\s*document\\s*}', 'bW')<CR>

    nnoremap <silent> <Plug>GotoPreviousPart	:<C-U>call atplib#motion#GotoSection("", v:count1, "sb", '\\\\part\\*\\=\\>', ( g:atp_mapNn ? 'atp' : 'vim' ))<CR>
    onoremap <silent> <Plug>GotoPreviousPart	:<C-U>call atplib#motion#GotoSection("", v:count1, "sb", '\\\\part\\*\\=\\>', 'vim')<CR>
    vnoremap <silent> <Plug>vGotoPreviousPart	m':<C-U>exe "normal! gv"<Bar>call search('\\\\\\%(part\\*\\=\\)\\>', 'bW')<CR>
endif


if &l:cpoptions =~# 'B'
    command! -buffer -bang -count=1 -nargs=? -complete=customlist,atplib#motion#Env_compl PSSSec		:call atplib#motion#GotoSection(<q-bang>, <q-count>, 'sb', '\\\%(\%(sub\)\{1,2}section\|section\|chapter\|part\)\*\=\>', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', <q-args>)
    command! -buffer -bang -count=1 -nargs=? -complete=customlist,atplib#motion#Env_compl PSSec		:call atplib#motion#GotoSection(<q-bang>, <q-count>, 'sb', '\\\%(subsection\|section\|chapter\|part\)\*\=\>', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', <q-args>)
    command! -buffer -bang -count=1 -nargs=? -complete=customlist,atplib#motion#Env_compl PSec		:call atplib#motion#GotoSection(<q-bang>, <q-count>, 'sb', '\\\%(section\|chapter\|part\)\*\=\>', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', <q-args>)
    command! -buffer -bang -count=1 -nargs=? -complete=customlist,atplib#motion#Env_compl PChap		:call atplib#motion#GotoSection(<q-bang>, <q-count>, 'sb', '\\\%(chapter\|part\)\*\=\>', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', <q-args>)
    command! -buffer -bang -count=1 -nargs=? -complete=customlist,atplib#motion#Env_compl PPart		:call atplib#motion#GotoSection(<q-bang>, <q-count>, 'sb', '\\part\*\=\>', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', <q-args>)
else
    command! -buffer -bang -count=1 -nargs=? -complete=customlist,atplib#motion#Env_compl PSSSec		:call atplib#motion#GotoSection(<q-bang>, <q-count>, 'sb', '\\\\\\%(\\%(sub\\)\\{1,2}section\\|section\\|chapter\\|part\\)\\*\\=\\>', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', <q-args>)
    command! -buffer -bang -count=1 -nargs=? -complete=customlist,atplib#motion#Env_compl PSSec		:call atplib#motion#GotoSection(<q-bang>, <q-count>, 'sb', '\\\\\\%(subsection\\|section\\|chapter\\|part\\)\\*\\=\\>', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', <q-args>)
    command! -buffer -bang -count=1 -nargs=? -complete=customlist,atplib#motion#Env_compl PSec		:call atplib#motion#GotoSection(<q-bang>, <q-count>, 'sb', '\\\\\\%(section\\|chapter\\|part\\)\\*\\=\\>', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', <q-args>)
    command! -buffer -bang -count=1 -nargs=? -complete=customlist,atplib#motion#Env_compl PChap		:call atplib#motion#GotoSection(<q-bang>, <q-count>, 'sb', '\\\\\\%(chapter\\|part\\)\\*\\=\\>', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', <q-args>)
    command! -buffer -bang -count=1 -nargs=? -complete=customlist,atplib#motion#Env_compl PPart		:call atplib#motion#GotoSection(<q-bang>, <q-count>, 'sb', '\\\\part\\*\\=\\>', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', <q-args>)
endif

command! -buffer NInput				:call atplib#motion#Input("w") 	| let v:searchforward = 1
command! -buffer PInput 			:call atplib#motion#Input("bw")	| let v:searchforward = 0
command! -buffer -nargs=? -bang -complete=customlist,atplib#motion#GotoFileComplete GotoFile	:call atplib#motion#GotoFile(<q-bang>,<q-args>, 0)
command! -buffer -nargs=? -bang -complete=customlist,atplib#motion#GotoFileComplete Edit 	:call atplib#motion#GotoFile(<q-bang>,<q-args>, 0)
command! -bang -nargs=? -complete=customlist,atplib#motion#GotoLabelCompletion GotoLabel  		:call atplib#motion#GotoLabel(<q-bang>, <q-args>)
" vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1
ftplugin/ATP_files/options.vim	[[[1
2792
" Author: 	Marcin Szamotulski	
" Description: 	This file contains all the options defined on startup of ATP
" Note:		This file is a part of Automatic Tex Plugin for Vim.
" Language:	tex
" Last Change: Sun Apr 22, 2012 at 11:43:10  +0100

" NOTE: you can add your local settings to ~/.atprc.vim or
" ftplugin/ATP_files/atprc.vim file

" Some options (functions) should be set once:
let s:did_options 	= exists("s:did_options") ? 1 : 0

"{{{ tab-local variables
" We need to know bufnumber and bufname in a tabpage.
" ToDo: we can set them with s: and call them using <SID> stack
" (how to make the <SID> stack invisible to the user!

    let t:atp_bufname	= expand("%:p")
    let t:atp_bufnr	= bufnr("")
    let t:atp_winnr	= winnr()


" autocommands for buf/win numbers
" These autocommands are used to remember the last opened buffer number and its
" window number:
if !s:did_options
    augroup ATP_TabLocalVariables
	au!
	au BufLeave *.tex 	let t:atp_bufname	= expand("%:p")
	au BufLeave *.tex 	let t:atp_bufnr		= bufnr("")
	" t:atp_winnr the last window used by tex, ToC or Labels buffers:
	au WinEnter *.tex 	let t:atp_winnr		= winnr("#")
	au WinEnter __ToC__ 	let t:atp_winnr		= winnr("#")
	au WinEnter __Labels__ 	let t:atp_winnr		= winnr("#")
	au TabEnter *.tex	let t:atp_SectionStack 	= ( exists("t:atp_SectionStack") ? t:atp_SectionStack : [] ) 
    augroup END
endif
"}}}

" ATP Debug Variables: (to debug atp behaviour)
" {{{ debug variables
if !exists("g:atp_debugCheckClosed")
    let g:atp_debugCheckClosed = 0
endif
if !exists("g:atp_debugMapFile")
    " debug of atplib#complete#CheckClosed_math function
    " (issues errormsg when synstack() failed).
    let g:atp_debugCheckClosed_math	= 0
endif
if !exists("g:atp_debugMapFile")
    " debug mappings.vim file (show which maps will not be defined).
    let g:atp_debugMapFile	= 0
endif
if !exists("g:atp_debugLatexTags")
    " debug <SID>LatexTags() function (motion.vim)
    let g:atp_debugLatexTags	= 0
endif
if !exists("g:atp_debugaaTeX")
    " debug <SID>auTeX() function (compiler.vim)
    let g:atp_debugauTeX	= 0
endif
if !exists("g:atp_debugSyncTex")
    " debug SyncTex (compiler.vim)
    let g:atp_debugSyncTex 	= 0
endif
if !exists("g:atp_debugInsertItem")
    " debug SyncTex (various.vim)
    let g:atp_debugInsertItem 	= 0
endif
if !exists("g:atp_debugUpdateATP")
    " debug UpdateATP (various.vim)
    let g:atp_debugUpdateATP 	= 0
endif
if !exists("g:atp_debugPythonCompiler")
    " debug MakeLatex (compiler.vim)
    let g:atp_debugPythonCompiler = 0
endif
if !exists("g:atp_debugML")
    " debug MakeLatex (compiler.vim)
    let g:atp_debugML		= 0
endif
if !exists("g:atp_debugGAF")
    " debug aptlib#GrepAuxFile
    let g:atp_debugGAF		= 0
endif
if !exists("g:atp_debugSelectCurrentParagraph")
    " debug s:SelectCurrentParapgrahp (LatexBox_motion.vim)
    let g:atp_debugSelectCurrentParagraph	= 0
endif
if !exists("g:atp_debugSIT")
    " debug <SID>SearchInTree (search.vim)
    let g:atp_debugSIT		= 0
endif
if !exists("g:atp_debugRS")
    " debug <SID>RecursiveSearch (search.vim)
    let g:atp_debugRS		= 0
endif
if !exists("g:atp_debugSync")
    " debug forward search (vim->viewer) (search.vim)
    let g:atp_debugSync		= 0
endif
if !exists("g:atp_debugV")
    " debug ViewOutput() (compiler.vim)
    let g:atp_debugV		= 0
endif
if !exists("g:atp_debugLPS")
    " Debug s:LoadProjectFile() (history.vim)
    " (currently it gives just the loading time info)
    let g:atp_debugLPS		= 0
endif
if !exists("g:atp_debugCompiler")
    " Debug s:Compiler() function (compiler.vim)
    " when equal 2 output is more verbose.
    let g:atp_debugCompiler 	= 0
endif
if !exists("g:atp_debugCallBack")
    " Debug <SID>CallBack() function (compiler.vim)
    let g:atp_debugCallBack	= 0
endif
if !exists("g:atp_debugST")
    " Debug SyncTex() (various.vim) function
    let g:atp_debugST 		= 0
endif
if !exists("g:atp_debugCloseLastEnvironment")
    " Debug atplib#complete#CloseLastEnvironment()
    let g:atp_debugCloseLastEnvironment	= 0
endif
if !exists("g:atp_debugMainScript")
    " loading times of scripts sources by main script file: ftpluing/tex_atp.vim
    " NOTE: it is listed here for completeness, it can only be set in
    " ftplugin/tex_atp.vim script file.
    let g:atp_debugMainScript 	= 0
endif

if !exists("g:atp_debugProject")
    " <SID>LoadScript(), <SID>LoadProjectScript(), <SID>WriteProject()
    " The value that is set in history file matters!
    let g:atp_debugProject 	= 0
endif
if !exists("g:atp_debugChekBracket")
    " atplib#complete#CheckBracket()
    let g:atp_debugCheckBracket 		= 0
endif
if !exists("g:atp_debugClostLastBracket")
    " atplib#complete#CloseLastBracket()
    let g:atp_debugCloseLastBracket 		= 0
endif
if !exists("g:atp_debugTabCompletion")
    " atplib#complete#TabCompletion()
    let g:atp_debugTabCompletion 		= 0
endif
if !exists("g:atp_debugBS")
    " atplib#bibsearch#searchbib()
    " atplib#bibsearch#showresults()
    " BibSearch() in ATP_files/search.vim
    " log file: /tmp/ATP_log 
    let g:atp_debugBS 		= 0
endif
if !exists("g:atp_debugToF")
    " TreeOfFiles() ATP_files/common.vim
    let g:atp_debugToF 		= 0
endif
if !exists("g:atp_debugBabel")
    " echo msg if  babel language is not supported.
    let g:atp_debugBabel 	= 0
endif
"}}}

" vim options
" {{{ Vim options

" Make CTRL-A, CTRL-X work over alphabetic characters:
setl nrformats=alpha
set  backupskip+=*.tex.project.vim

" The vim option 'iskeyword' is adjust just after g:atp_separator and
" g:atp_no_separator variables are defined.
setl keywordprg=texdoc\ -m
if maparg("K", "n") != ""
    try
	nunmap <buffer> K
    catch E31:
	nunmap K
    endtry
endif

exe "setlocal complete+=".
	    \ "k".split(globpath(&rtp, "ftplugin/ATP_files/dictionaries/greek"), "\n")[0].
	    \ ",k".split(globpath(&rtp, "ftplugin/ATP_files/dictionaries/dictionary"), "\n")[0].
	    \ ",k".split(globpath(&rtp, "ftplugin/ATP_files/dictionaries/SIunits"), "\n")[0].
	    \ ",k".split(globpath(&rtp, "ftplugin/ATP_files/dictionaries/tikz"), "\n")[0]

" The ams_dictionary is added after g:atp_amsmath variable is defined.

" setlocal iskeyword+=\
let suffixes = split(&suffixes, ",")
if index(suffixes, ".pdf") == -1
    setlocal suffixes+=.pdf
elseif index(suffixes, ".dvi") == -1
    setlocal suffixes+=.dvi
endif
" As a base we use the standard value defined in 
" The suffixes option is also set after g:atp_tex_extensions is set.

" Borrowed from tex.vim written by Benji Fisher:
    " Set 'comments' to format dashed lists in comments
    setlocal comments=sO:%\ -,mO:%\ \ ,eO:%%,:%
"     setlocal comments=n:%,s:%,m:%,e:%

    " Set 'commentstring' to recognize the % comment character:
    " (Thanks to Ajit Thakkar.)
    setlocal commentstring=%%s

    " Allow "[d" to be used to find a macro definition:
    " Recognize plain TeX \def as well as LaTeX \newcommand and \renewcommand .
    " I may as well add the AMS-LaTeX DeclareMathOperator as well.
    let &l:define='\\\([egx]\|char\|mathchar\|count\|dimen\|muskip\|skip\|toks\)\=def'
	    \ .	'\|\\font\|\\\(future\)\=let'
	    \ . '\|\\new\(count\|dimen\|skip\|muskip\|box\|toks\|read\|write\|fam\|insert\)'
	    \ .	'\|\\definecolor{'
	    \ . '\|\\\(re\)\=new\(boolean\|command\|counter\|environment\|font'
	    \ . '\|if\|length\|savebox\|theorem\(style\)\=\)\s*\*\=\s*{\='
	    \ . '\|DeclareMathOperator\s*{\=\s*'
	    \ . '\|DeclareFixedFont\s*{\s*'
    if &l:filetype != "plaintex"
	setlocal include=^[^%]*\\%(\\\\input\\(\\s*{\\)\\=\\\\|\\\\include\\s*{\\)
    else
	setlocal include=^[^%]*\\\\input
    endif
    setlocal suffixesadd=.tex

    setlocal includeexpr=substitute(v:fname,'\\%(.tex\\)\\?$','.tex','')
    " TODO set define and work on the above settings, these settings work with [i
    " command but not with [d, [D and [+CTRL D (jump to first macro definition)
    
    " AlignPlugin settings
    if !exists("g:Align_xstrlen") && v:version >= 703 && &conceallevel 
	let g:Align_xstrlen="ATP_strlen"
    endif
" }}}

" BUFFER LOCAL VARIABLES:
" {{{ buffer variables
let b:atp_running	= 0

if has("mac") || has("macunix")
    let b:atp_openOptions = " -a Skim "
endif

" these are all buffer related variables:
function! <SID>TexCompiler()
    if exists("b:atp_TexCompiler")
	return b:atp_TexCompiler
    elseif buflisted(atplib#FullPath(b:atp_MainFile))
	let line = get(getbufline(atplib#FullPath(b:atp_MainFile), 1), 0, "")
	if line =~ '^%&\w*tex\>'
	    return matchstr(line, '^%&\zs\w\+')
	endif
    elseif filereadable(atplib#FullPath(b:atp_MainFile))
	let line = get(readfile(atplib#FullPath(b:atp_MainFile)), 0, "")
	if line =~ '^%&\w*tex\>'
	    return matchstr(line, '^%&\zs\w\+')
	endif
    endif
    return (&filetype == "plaintex" ? "pdftex" : "pdflatex")
endfunction
    
let s:optionsDict= { 	
		\ "atp_TexOptions" 		: "-synctex=1", 
	        \ "atp_ReloadOnError" 		: "1", 
		\ "atp_OpenViewer" 		: "1", 		
		\ "atp_autex" 			: !&l:diff && expand("%:e") == 'tex', 
		\ "atp_autex_wait"		: 0,
		\ "atp_updatetime_insert"	: 4000,
		\ "atp_updatetime_normal"	: 2000,
		\ "atp_MaxProcesses"		: 3,
		\ "atp_KillYoungest"		: 0,
		\ "atp_ProjectScript"		: ( fnamemodify(b:atp_MainFile, ":e") != "tex" ? "0" : "1" ),
		\ "atp_Viewer" 			: has("win26") || has("win32") || has("win64") || has("win95") || has("win32unix") ? "AcroRd32.exe" : ( has("mac") || has("macunix") ? "open" : "okular" ), 
		\ "atp_TexFlavor" 		: &l:filetype, 
		\ "atp_XpdfServer" 		: fnamemodify(b:atp_MainFile,":t:r"), 
		\ "atp_LocalXpdfServer" 	: expand("%:t:r"), 
		\ "atp_okularOptions"		: ["--unique"],
		\ "atp_TempDir"			: substitute(b:atp_OutDir . "/.tmp", '\/\/', '\/', 'g'),
		\ "atp_OutDir"			: ( exists("b:atp_ProjectScriptFile") ? fnamemodify(b:atp_ProjectScriptFile, ":h") : fnamemodify(resolve(expand("%:p")), ":h") ),
		\ "atp_TexCompiler" 		: <SID>TexCompiler(),
		\ "atp_BibCompiler"		: ( getline(atplib#search#SearchPackage('biblatex')) =~ '\<backend\s*=\s*biber\>' ? 'biber' : "bibtex" ),
		\ "atp_auruns"			: "1",
		\ "atp_TruncateStatusSection"	: "60", 
		\ "atp_LastBibPattern"		: "",
		\ "atp_TexCompilerVariable"	: "max_print_line=2000",
		\ "atp_StarEnvDefault"		: "",
		\ "atp_StarMathEnvDefault"	: "",
		\ "atp_LatexPIDs"		: [],
		\ "atp_BibtexPIDs"		: [],
		\ "atp_PythonPIDs"		: [],
		\ "atp_MakeindexPIDs"		: [],
		\ "atp_LastLatexPID"		: 0,
		\ "atp_LastPythonPID"		: 0,
		\ "atp_VerboseLatexInteractionMode" : "errorstopmode",
		\ "atp_BibtexReturnCode"	: 0,
		\ "atp_MakeidxReturnCode"	: 0,
		\ "atp_BibtexOutput"		: "",
		\ "atp_MakeidxOutput"		: "",
		\ "atp_DocumentClass"		: atplib#search#DocumentClass(b:atp_MainFile)}

" Note: the above atp_OutDir is not used! the function s:SetOutDir() is used, it is just to
" remember what is the default used by s:SetOutDir().

" This function sets options (values of buffer related variables) which were
" not already set by the user.
" {{{ s:SetOptions
let s:ask = { "ask" : "0" }
function! s:SetOptions()

    let s:optionsKeys		= keys(s:optionsDict)
    let s:optionsinuseDict	= getbufvar(bufname("%"),"")

    "for each key in s:optionsKeys set the corresponding variable to its default
    "value unless it was already set in .vimrc file.
    for key in s:optionsKeys
" 	echomsg key
	if string(get(s:optionsinuseDict,key, "optionnotset")) == string("optionnotset") && key != "atp_OutDir" && key != "atp_autex"
	    call setbufvar(bufname("%"), key, s:optionsDict[key])
	elseif key == "atp_OutDir"

	    " set b:atp_OutDir and the value of errorfile option
	    if !exists("b:atp_OutDir")
		call atplib#common#SetOutDir(1)
	    endif
	    let s:ask["ask"] 	= 1
	endif
    endfor

        " Do not run tex on tex files which are in texmf tree
    " Exception: if it is opened using the command ':EditInputFile'
    " 		 which sets this itself.
    let time=reltime()
    if string(get(s:optionsinuseDict,"atp_autex", 'optionnotset')) == string('optionnotset')
	let atp_texinputs=split(substitute(substitute(system("kpsewhich -show-path tex"),'\/\/\+','\/','g'),'!\|\n','','g'),':')
	call remove(atp_texinputs, index(atp_texinputs, '.'))
	call filter(atp_texinputs, 'b:atp_OutDir =~# v:val')
	let b:atp_autex = ( len(atp_texinputs) ? 0 : s:optionsDict['atp_autex'])  
    endif
    let g:source_time_INPUTS=reltimestr(reltime(time))

    let time=reltime()
    if !exists("b:TreeOfFiles") || !exists("b:ListOfFiles") || !exists("b:TypeDict") || !exists("b:LevelDict")
	if exists("b:atp_MainFile") 
	    let atp_MainFile	= atplib#FullPath(b:atp_MainFile)
	    call TreeOfFiles(atp_MainFile, g:atp_inputfile_pattern, (&filetype == 'plaintex' ? 1 : 0))
	else
	    echomsg "[ATP:] b:atp_MainFile: ".b:atp_MainFile." doesn't exists."
	endif
    endif
    let g:source_time_TREE=reltimestr(reltime(time))
endfunction
"}}}
call s:SetOptions()

"}}}

" GLOBAL VARIABLES: (almost all)
" {{{ global variables 
if !exists("g:atp_indent")
    let g:atp_indent=1
endif
if !exists("g:atp_DisplaylinePath")
    let g:atp_DisplaylinePath = "/Applications/Skim.app/Contents/SharedSupport/displayline"
endif
" if !exists("g:atp_ParseLog") " is set in ftplugin/ATP_files/common.vim script.
"     let g:atp_ParseLog = has("python")
" endif
" if !exists("g:atp_autocclose")
"     " This can be done by setting g:atp_DefautDebugMode = 'debug' (but it
"     not documented and not tested)
"     let g:atp_autocclose = 0
" endif
if !exists("g:atp_diacritics_letters")
    let g:atp_diacritics_letters={}
endif
let s:diacritics_letters = {
	    \ "'"  : 'aceginorsuyz',
	    \ "\"" : 'aeiouy',
	    \ "`"  : 'aeiouy',
	    \ "^"  : 'aceghilosuwy',
	    \ "v"  : 'acdehlnrstuz',
	    \ "b"  : '',
	    \ "d"  : '',
	    \ "H"  : 'ou',
	    \ "~"  : 'aeinouy',
	    \ "."  : 'acegioz',
	    \ "c"  : 'cegklnrst',
	    \ "t"  : '',
	    \ "2"  : '' }
for key in keys(s:diacritics_letters)
    if !has_key(g:atp_diacritics_letters, key)
	let g:atp_diacritics_letters[key] = s:diacritics_letters[key]
    endif
endfor
if !exists("g:atp_python_toc")
    let g:atp_python_toc = has("python")
endif
if !exists("g:atp_write_eventignore")
    " This is a comma separated list of events which will be ignored when 
    " atp saved the file (for example before background compilation but not
    " with :TEX command)
    let g:atp_write_eventignore=""
    " This was added to make:
    " au BufWrite *.tex :call atplib#motion#LatexTags('', 1) "silently make tags file
endif
if !exists("g:atp_ProgressBarValues")
    let g:atp_ProgressBarValues = {}
endif
if get(g:atp_ProgressBarValues,bufnr("%"),{}) == {}
    call extend(g:atp_ProgressBarValues, { bufnr("%") : {} })
endif
" if !exists("g:atp_TempDir")
"     " Is set in project.vim script.
"     call atplib#TempDir()
" endif
if !exists("g:atp_LogStatusLine")
    let g:atp_LogStatusLine = 0
endif
if !exists("g:atp_OpenAndSyncSleepTime")
    let g:atp_OpenAndSyncSleepTime = "750m"
endif
if !exists("g:atp_tab_map")
    let g:atp_tab_map = 0
endif
if !exists("g:atp_folding")
    let g:atp_folding = 0
endif
if !exists("g:atp_devversion")
    let g:atp_devversion = 0
endif
if !exists("g:atp_completion_tikz_expertmode")
    let g:atp_completion_tikz_expertmode = 1
endif
if !exists("g:atp_signs")
    let g:atp_signs = 0
endif
if !exists("g:atp_TexAlign_join_lines")
    let g:atp_TexAlign_join_lines = 0
endif
" if !exists("g:atp_imap_put_space") || g:atp_imap_put_space
" This was not working :(.
"     let g:atp_imap_put_space 	= 1
" endif
if !exists("g:atp_imap_tilde_braces")
    let g:atp_imap_tilde_braces = 0
endif
if !exists("g:atp_diacritics")
    let g:atp_diacritics = 2
endif
if !exists("g:atp_imap_diffop_move")
    let g:atp_imap_diffop_move 	= 0
endif
if !exists("g:atp_noautex_in_math")
    let g:atp_noautex_in_math 	= 1
endif
if !exists("g:atp_cmap_space")
    let g:atp_cmap_space 	= 1
endif
if !exists("g:atp_bibsearch")
    " Use python search engine (and python regexp) for bibsearch
    let g:atp_bibsearch 	= "python"
endif
if !exists("g:atp_map_Comment")
    let g:atp_map_Comment 	= "-c"
endif
if !exists("g:atp_map_UnComment")
    let g:atp_map_UnComment 	= "-u"
endif
if !exists("g:atp_HighlightErrors")
    let g:atp_HighlightErrors 	= 0
endif
if !exists("g:atp_Highlight_ErrorGroup")
    let g:atp_Highlight_ErrorGroup = "Error"
endif
if !exists("g:atp_Highlight_WarningGroup")
"     let g:atp_Highlight_WarningGroup = "WarningMsg"
    let g:atp_Highlight_WarningGroup = ""
endif
if !exists("maplocalleader")
    if &l:cpoptions =~# "B"
	let maplocalleader="\\"
    else
	let maplocalleader="\\\\"
    endif
endif
if !exists("g:atp_sections")
    " Used by :TOC command (s:maketoc in motion.vim)
    let g:atp_sections={
	\	'chapter' 	: [ '\m^\s*\(\\chapter\*\?\>\)',			'\m\\chapter\*'		],	
	\	'section' 	: [ '\m^\s*\(\\section\*\?\>\)',			'\m\\section\*'		],
	\ 	'subsection' 	: [ '\m^\s*\(\\subsection\*\?\>\)',			'\m\\subsection\*'	],
	\	'subsubsection' : [ '\m^\s*\(\\subsubsection\*\?\>\)',			'\m\\subsubsection\*'	],
	\	'bibliography' 	: [ '\m^\s*\(\\begin\s*{\s*thebibliography\s*}\|\\bibliography\s*{\)' , 'nopattern'],
	\	'abstract' 	: [ '\m^\s*\(\\begin\s*{abstract}\|\\abstract\s*{\)',	'nopattern'		],
	\   	'part'		: [ '\m^\s*\(\\part\*\?\>\)',				'\m\\part\*'		],
	\   	'frame'		: [ '\m^\s*\(\\frametitle\*\?\>\)',			'\m\\frametitle\*'	]
	\ }
endif
if !exists("g:atp_cgetfile")
    let g:atp_cgetfile = 1
endif
if !exists("g:atp_atpdev")
    " if 1 defines DebugPrint command to print log files from g:atp_Temp directory.
    let g:atp_atpdev = 0
endif
if !exists("g:atp_imap_ShortEnvIMaps")
    " By default 1, then one letter (+leader) mappings for environments are defined,
    " for example ]t -> \begin{theorem}\end{theorem}
    " if 0 three letter maps are defined: ]the -> \begin{theorem}\end{theorem}
    let g:atp_imap_ShortEnvIMaps = 1
endif
if !exists("g:atp_imap_over_leader")
    " I'm not using "'" by default - because it is used quite often in mathematics to
    " denote symbols.
    let g:atp_imap_over_leader	= "`"
endif
if !exists("g:atp_imap_subscript")
    let g:atp_imap_subscript 	= "__"
endif
if !exists("g:atp_imap_supscript")
    let g:atp_imap_supscript	= "^"
endif
if !exists("g:atp_imap_define_math")
    let g:atp_imap_define_math	= 1
endif
if !exists("g:atp_imap_define_environments")
    let g:atp_imap_define_environments = 1
endif
if !exists("g:atp_imap_define_math_misc")
    let g:atp_imap_define_math_misc = 1
endif
if !exists("g:atp_imap_define_diacritics")
    let g:atp_imap_define_diacritics = 1
endif
if !exists("g:atp_imap_define_greek_letters")
    let g:atp_imap_define_greek_letters = 1
endif
if !exists("g:atp_imap_wide")
    let g:atp_imap_wide		= 0
endif
if !exists("g:atp_letter_opening")
    let g:atp_letter_opening	= ""
endif
if !exists("g:atp_letter_closing")
    let g:atp_letter_closing	= ""
endif
if !exists("g:atp_imap_bibiliography")
    if g:atp_imap_ShortEnvIMaps
	let g:atp_imap_letter=""
    else
	let g:atp_imap_letter="let"
    endif
endif
if !exists("g:atp_imap_bibiliography")
    if g:atp_imap_ShortEnvIMaps
	let g:atp_imap_bibliography="B"
    else
	let g:atp_imap_bibliography="bib"
    endif
endif
if !exists("g:atp_imap_begin")
    if g:atp_imap_ShortEnvIMaps
	let g:atp_imap_begin="b"
    else
	let g:atp_imap_begin="beg"
    endif
endif
if !exists("g:atp_imap_end")
    if g:atp_imap_ShortEnvIMaps
	let g:atp_imap_end="e"
    else
	let g:atp_imap_end="end"
    endif
endif
if !exists("g:atp_imap_theorem")
    if g:atp_imap_ShortEnvIMaps
	let g:atp_imap_theorem="t"
    else
	let g:atp_imap_theorem="the"
    endif
endif
if !exists("g:atp_imap_definition")
    if g:atp_imap_ShortEnvIMaps
	let g:atp_imap_definition="d"
    else
	let g:atp_imap_definition="def"
    endif
endif
if !exists("g:atp_imap_proposition")
    if g:atp_imap_ShortEnvIMaps
	let g:atp_imap_proposition="P"
    else
	let g:atp_imap_proposition="Pro"
    endif
endif
if !exists("g:atp_imap_lemma")
    if g:atp_imap_ShortEnvIMaps
	let g:atp_imap_lemma="l"
    else
	let g:atp_imap_lemma="lem"
    endif
endif
if !exists("g:atp_imap_remark")
    if g:atp_imap_ShortEnvIMaps
	let g:atp_imap_remark="r"
    else
	let g:atp_imap_remark="rem"
    endif
endif
if !exists("g:atp_imap_corollary")
    if g:atp_imap_ShortEnvIMaps
	let g:atp_imap_corollary="c"
    else
	let g:atp_imap_corollary="cor"
    endif
endif
if !exists("g:atp_imap_proof")
    if g:atp_imap_ShortEnvIMaps
	let g:atp_imap_proof="p"
    else
	let g:atp_imap_proof="pro"
    endif
endif
if !exists("g:atp_imap_example")
    if g:atp_imap_ShortEnvIMaps
	let g:atp_imap_example="x"
    else
	let g:atp_imap_example="exa"
    endif
endif
if !exists("g:atp_imap_note")
    if g:atp_imap_ShortEnvIMaps
	let g:atp_imap_note="n"
    else
	let g:atp_imap_note="not"
    endif
endif
if !exists("g:atp_imap_enumerate")
    if g:atp_imap_ShortEnvIMaps
	let g:atp_imap_enumerate="E"
    else
	let g:atp_imap_enumerate="enu"
    endif
endif
if !exists("g:atp_imap_tabular")
    if g:atp_imap_ShortEnvIMaps
	let g:atp_imap_tabular="T"
    else
	let g:atp_imap_tabular="tab"
    endif
endif
if !exists("g:atp_imap_table")
    if g:atp_imap_ShortEnvIMaps
	let g:atp_imap_table=""
    else
	let g:atp_imap_table="Tab"
    endif
endif
if !exists("g:atp_imap_itemize")
    if g:atp_imap_ShortEnvIMaps
	let g:atp_imap_itemize="I"
    else
	let g:atp_imap_itemize="ite"
    endif
endif
if !exists("g:atp_imap_item")
    if g:atp_imap_ShortEnvIMaps
	let g:atp_imap_item="i"
    else
	let g:atp_imap_item="I"
    endif
endif
if !exists("g:atp_imap_align")
    if g:atp_imap_ShortEnvIMaps
	let g:atp_imap_align="a"
    else
	let g:atp_imap_align="ali"
    endif
endif
if !exists("g:atp_imap_multiline")
    " Is not defined by default: ]m, and ]M are used for \(:\) and \[:\].
    if g:atp_imap_ShortEnvIMaps
	let g:atp_imap_multiline=""
    else
	let g:atp_imap_multiline="lin"
    endif
endif
if !exists("g:atp_imap_abstract")
    if g:atp_imap_ShortEnvIMaps
	let g:atp_imap_abstract="A"
    else
	let g:atp_imap_abstract="abs"
    endif
endif
if !exists("g:atp_imap_equation")
    if g:atp_imap_ShortEnvIMaps
	let g:atp_imap_equation="q"
    else
	let g:atp_imap_equation="equ"
    endif
endif
if !exists("g:atp_imap_center")
    if g:atp_imap_ShortEnvIMaps
	let g:atp_imap_center="C"
    else
	let g:atp_imap_center="cen"
    endif
endif
if !exists("g:atp_imap_flushleft")
    if g:atp_imap_ShortEnvIMaps
	let g:atp_imap_flushleft="L"
    else
	let g:atp_imap_flushleft="lef"
    endif
endif
if !exists("g:atp_imap_flushright")
    if g:atp_imap_ShortEnvIMaps
	let g:atp_imap_flushright="R"
    else
	let g:atp_imap_flushright="rig"
    endif
endif
if !exists("g:atp_imap_tikzpicture")
    if g:atp_imap_ShortEnvIMaps
	let g:atp_imap_tikzpicture="T"
    else
	let g:atp_imap_tikzpicture="tik"
    endif
endif
if !exists("g:atp_imap_frame")
    if g:atp_imap_ShortEnvIMaps
	let g:atp_imap_frame="f"
    else
	let g:atp_imap_frame="fra"
    endif
endif
if !exists("g:atp_goto_section_leader")
    let g:atp_goto_section_leader="-"
endif
if !exists("g:atp_autex_wait")
    " the value is a comma speareted list of modes, for modes see mode() function.
"     let g:atp_autex_wait = "i,R,Rv,no,v,V,c,cv,ce,r,rm,!"
    let g:atp_autex_wait = ""
endif
if !exists("g:atp_MapSelectComment")
    let g:atp_MapSelectComment = "=c"
endif
if exists("g:atp_latexpackages")
    " Transition to nicer name:
    let g:atp_LatexPackages = g:atp_latexpackages
    unlet g:atp_latexpackages
endif
if !exists("g:texmf")
    let g:texmf = substitute(system("kpsewhich -expand-var='$TEXMFHOME'"), '\n', '', 'g')
endif
if exists("g:atp_LatexPackages")
    " Rescan the $TEXMFHOME directory for sty and tex files.
    let time = reltime()
    let sty_files = atplib#search#KpsewhichGlobPath('tex', g:texmf."/**", '*.\(sty\|tex\)', ':p')
    for file in sty_files
	if index(g:atp_LatexPackages, file) == -1
	    call add(g:atp_LatexPackages, file)
	endif
    endfor
    let g:time_UpdateStyFiles = reltimestr(reltime(time))
endif
if exists("g:atp_LatexClasses")
    " Rescan the $TEXMFHOME directory for cls files.
    let time = reltime()
    let cls_files = atplib#search#KpsewhichGlobPath('tex', g:texmf."/**", '*.cls', ':p')
    for file in cls_files
	if index(g:atp_LatexClasses, file) == -1
	    call add(g:atp_LatexClasses, file)
	endif
    endfor
    let g:time_UpdateClsFiles = reltimestr(reltime(time))
endif
if exists("g:atp_latexclasses")
    " Transition to nicer name:
    let g:atp_LatexClasses = g:atp_latexclasses
    unlet g:atp_latexclasses
endif
if !exists("g:atp_Python")
    " Also set in atplib#various#GetLatestSnapshot() and atplib#various#UpdateATP()
    " This might be a name of python executable or full path to it (if it is not in
    " the $PATH) 
    if has("win32") || has("win64")
	" TO BE TESTED:
	" see why to use "pythonw.exe" on:
	" "http://docs.python.org/using/windows.html".
	let g:atp_Python = "pythonw.exe"
    else
	let g:atp_Python = "python"
    endif
endif
if !exists("g:atp_UpdateToCLine")
    let g:atp_UpdateToCLine = 1
endif
if !exists("g:atp_DeleteWithBang")
    let g:atp_DeleteWithBang = [ 'synctex.gz', 'tex.project.vim']
endif
if !exists("g:atp_CommentLeader")
    let g:atp_CommentLeader="% "
endif
if !exists("g:atp_MapCommentLines")
    let g:atp_MapCommentLines = 1
endif
if !exists("g:atp_XpdfSleepTime")
    let g:atp_XpdfSleepTime = "0"
endif
if !exists("g:atp_IMapCC")
    let g:atp_IMapCC = 0
endif
if !exists("g:atp_DefaultErrorFormat")
    let g:atp_DefaultErrorFormat = "erc"
endif
let b:atp_ErrorFormat = g:atp_DefaultErrorFormat
if !exists("g:atp_DsearchMaxWindowHeight")
    let g:atp_DsearchMaxWindowHeight=15
endif
if !exists("g:atp_ProgressBar")
    let g:atp_ProgressBar = 1
endif
let g:atp_cmdheight = &l:cmdheight
if !exists("g:atp_DebugModeQuickFixHeight")
    let g:atp_DebugModeQuickFixHeight = 8 
endif
if !exists("g:atp_DebugModeCmdHeight")
    let g:atp_DebugModeCmdHeight = &l:cmdheight
endif
if !exists("g:atp_DebugMode_AU_change_cmdheight")
    " Background Compilation will change the 'cmdheight' option when the compilation
    " was without errors. AU - autocommand compilation
    let g:atp_DebugMode_AU_change_cmdheight = 0
    " This is the 'stay out of my way' solution. 
endif
if !exists("g:atp_Compiler")
    let g:atp_Compiler = "python"
endif
if !exists("g:atp_ReloadViewers")
    " List of viewers which need to be reloaded after output file is updated.
    let g:atp_ReloadViewers	= [ 'xpdf' ]
endif
if !exists("g:atp_PythonCompilerPath")
    let g:atp_PythonCompilerPath=fnamemodify(expand("<sfile>"), ":p:h")."/compile.py"
endif
if !exists("g:atp_cpcmd")
    let g:atp_cpcmd="/bin/cp"
endif
" Variables for imaps, standard environment names:
if !exists("g:atp_EnvNameTheorem")
    let g:atp_EnvNameTheorem="theorem"
endif
if !exists("g:atp_EnvNameDefinition")
    let g:atp_EnvNameDefinition="definition"
endif
if !exists("g:atp_EnvNameProposition")
    let g:atp_EnvNameProposition="proposition"
endif
if !exists("g:atp_EnvNameObservation")
    " This mapping is defined only in old layout:
    " i.e. if g:atp_env_maps_old == 1
    let g:atp_EnvNameObservation="observation"
endif
if !exists("g:atp_EnvNameLemma")
    let g:atp_EnvNameLemma="lemma"
endif
if !exists("g:atp_EnvNameNote")
    let g:atp_EnvNameNote="note"
endif
if !exists("g:atp_EnvNameCorollary")
    let g:atp_EnvNameCorollary="corollary"
endif
if !exists("g:atp_EnvNameRemark")
    let g:atp_EnvNameRemark="remark"
endif
if !exists("g:atp_EnvNameExample")
    let g:atp_EnvNameExample="example"
endif
if !exists("g:atp_EnvOptions_enumerate")
    " add options to \begin{enumerate} for example [topsep=0pt,noitemsep] Then the
    " enumerate map <Leader>E will put \begin{enumerate}[topsep=0pt,noitemsep] Useful
    " options of enumitem to make enumerate more condenced.
    let g:atp_EnvOptions_enumerate=""
endif
if !exists("g:atp_EnvOptions_itemize")
    " Similar to g:atp_enumerate_options.
    let g:atp_EnvOptions_itemize=""
endif
if !exists("g:atp_VimCompatible")
    " Used by: % (s:JumpToMatch in LatexBox_motion.vim).
    " Remap :normal! r to <SID>Replace() (various.vim)
    let g:atp_VimCompatible = 0
    " It can be 0/1 or yes/no.
endif 
if !exists("g:atp_CupsOptions")
    " lpr command options for completion of SshPrint command.
    let g:atp_CupsOptions = [ 'landscape=', 'scaling=', 'media=', 'sides=', 'Collate=', 'orientation-requested=', 
		\ 'job-sheets=', 'job-hold-until=', 'page-ragnes=', 'page-set=', 'number-up=', 'page-border=', 
		\ 'number-up-layout=', 'fitplot=', 'outputorder=', 'mirror=', 'raw=', 'cpi=', 'columns=',
		\ 'page-left=', 'page-right=', 'page-top=', 'page-bottom=', 'prettyprint=', 'nowrap=', 'position=',
		\ 'natural-scaling=', 'hue=', 'ppi=', 'saturation=', 'blackplot=', 'penwidth=']
endif
if !exists("g:atp_lprcommand")
    " Used by :SshPrint
    let g:atp_lprcommand = "lpr"
endif 
if !exists("g:atp_iabbrev_leader")
    " Used for abbreviations: =theorem= (from both sides).
    let g:atp_iabbrev_leader = "="
endif 
if !exists("g:atp_bibrefRegister")
    " A register to which bibref obtained from AMS will be copied.
    let g:atp_bibrefRegister = "0"
endif
if !exists("g:atpbib_pathseparator")
    if has("win16") || has("win32") || has("win64") || has("win95")
	let g:atpbib_pathseparator = "\\"
    else
	let g:atpbib_pathseparator = "/"
    endif 
endif
if !exists("g:atpbib_WgetOutputFile")
    let g:atpbib_WgetOutputFile = "amsref.html"
endif
if !exists("g:atpbib_wget")
    let g:atpbib_wget="wget"
endif
if !exists("g:atp_vmap_text_font_leader")
    let g:atp_vmap_text_font_leader="_"
endif
if !exists("g:atp_vmap_environment_leader")
    let g:atp_vmap_environment_leader="<LocalLeader>"
endif
if !exists("g:atp_vmap_bracket_leader")
    let g:atp_vmap_bracket_leader="<LocalLeader>"
endif
if !exists("g:atp_vmap_big_bracket_leader")
    let g:atp_vmap_big_bracket_leader='<LocalLeader>b'
endif
if !exists("g:atp_map_forward_motion_leader")
    let g:atp_map_forward_motion_leader='>'
endif
if !exists("g:atp_map_backward_motion_leader")
    let g:atp_map_backward_motion_leader='<'
endif
if !exists("g:atp_RelativePath")
    " This is here only for completness, the default value is set in project.vim
    let g:atp_RelativePath 	= 1
endif
if !exists("g:atp_SyncXpdfLog")
    let g:atp_SyncXpdfLog 	= 0
endif
if !exists("g:atp_LogSync")
    let g:atp_LogSync 		= 0
endif

function! s:Sync(...)
    let arg = ( a:0 >=1 ? a:1 : "" )
    if arg == "on"
	let g:atp_LogSync = 1
    elseif arg == "off"
	let g:atp_LogSync = 0
    else
	let g:atp_LogSync = !g:atp_LogSync
    endif
    echomsg "[ATP:] g:atp_LogSync = " . g:atp_LogSync
endfunction
command! -buffer -nargs=? -complete=customlist,s:SyncComp LogSync :call s:Sync(<f-args>)
function! s:SyncComp(ArgLead, CmdLine, CursorPos)
    return filter(['on', 'off'], "v:val =~ a:ArgLead") 
endfunction

if !exists("g:atp_Compare")
    " Use b:changedtick variable to run s:Compiler automatically.
    let g:atp_Compare = "changedtick"
endif
if !exists("g:atp_babel")
    let g:atp_babel = 0
endif
" if !exists("g:atp_closebracket_checkenv")
    " This is a list of environment names. They will be checked by
    " atplib#complete#CloseLastBracket() function (if they are opened/closed:
    " ( \begin{array} ... <Tab>       will then close first \begin{array} and then ')'
    try
	let g:atp_closebracket_checkenv	= [ 'array' ]
	" Changing this variable is not yet supported *see ToDo: in
	" atplib#complete#CloseLastBracket() (autoload/atplib.vim)
	lockvar g:atp_closebracket_checkenv
    catch /E741:/
    endtry
" endif
" if !exists("g:atp_ProjectScript")
"     let g:atp_ProjectScript = 1
" endif
if !exists("g:atp_OpenTypeDict")
    let g:atp_OpenTypeDict = { 
		\ "pdf" 	: "xpdf",		"ps" 	: "evince",
		\ "djvu" 	: "djview",		"txt" 	: "split" ,
		\ "tex"		: "edit",		"dvi"	: "xdvi -s 5" }
    " for txt type files supported viewers: cat, gvim = vim = tabe, split, edit
endif
if !exists("g:atp_LibraryPath")
    let g:atp_LibraryPath	= 0
endif
if !exists("g:atp_statusOutDir")
    let g:atp_statusOutDir 	= 1
endif
if !exists("g:atp_developer")
    let g:atp_developer		= 0
endif
if !exists("g:atp_mapNn")
	let g:atp_mapNn		= 0 " This value is used only on startup, then :LoadHistory sets the default value.
endif  				    " user cannot change the value set by :LoadHistory on startup in atprc file.
" 				    " Unless using: 
" 				    	au VimEnter *.tex let b:atp_mapNn = 0
" 				    " Recently I changed this: in project files it is
" 				    better to start with atp_mapNn = 0 and let the
" 				    user change it. 
if !exists("g:atp_TeXdocDefault")
    let g:atp_TeXdocDefault	= '-I lshort'
endif
"ToDo: to doc.
"ToDo: luatex! (can produce both!)
if !exists("g:atp_CompilersDict")
    let g:atp_CompilersDict 	= { 
		\ "pdflatex" 	: ".pdf", 	"pdftex" 	: ".pdf", 
		\ "xetex" 	: ".pdf", 	"latex" 	: ".dvi", 
		\ "tex" 	: ".dvi",	"elatex"	: ".dvi",
		\ "etex"	: ".dvi", 	"luatex"	: ".pdf"}
endif

if !exists("g:CompilerMsg_Dict")
    let g:CompilerMsg_Dict	= { 
		\ 'tex'			: 'TeX', 
		\ 'etex'		: 'eTeX', 
		\ 'pdftex'		: 'pdfTeX', 
		\ 'latex' 		: 'LaTeX',
		\ 'elatex' 		: 'eLaTeX',
		\ 'pdflatex'		: 'pdfLaTeX', 
		\ 'context'		: 'ConTeXt',
		\ 'luatex'		: 'LuaTeX',
		\ 'xetex'		: 'XeTeX'}
endif

if !exists("g:ViewerMsg_Dict")
    let g:ViewerMsg_Dict	= {
		\ 'xpdf'		: 'Xpdf',
		\ 'xdvi'		: 'Xdvi',
		\ 'kpdf'		: 'Kpdf',
		\ 'okular'		: 'Okular', 
		\ 'open'		: 'open',
		\ 'skim'		: 'Skim', 
		\ 'evince'		: 'Evince',
		\ 'acroread'		: 'AcroRead',
		\ 'epdfview'		: 'epdfView' }
endif
if b:atp_updatetime_normal
    let &l:updatetime=b:atp_updatetime_normal
endif
if !exists("g:atp_DefaultDebugMode")
    " recognised values: silent, debug.
    let g:atp_DefaultDebugMode	= "silent"
endif
if !exists("g:atp_show_all_lines")
    " boolean
    let g:atp_show_all_lines 	= 0
endif
if !exists("g:atp_ignore_unmatched")
    " boolean
    let g:atp_ignore_unmatched 	= 1
endif
if !exists("g:atp_imap_leader_1")
    let g:atp_imap_leader_1	= "#"
endif
if !exists("g:atp_infty_leader")
    let g:atp_infty_leader = (g:atp_imap_leader_1 == '#' ? '`' : g:atp_imap_leader_1 ) 
endif
if !exists("g:atp_imap_leader_2")
    let g:atp_imap_leader_2= "##"
endif
if !exists("g:atp_imap_leader_3")
    let g:atp_imap_leader_3	= "]"
endif
if !exists("g:atp_imap_leader_4")
    let g:atp_imap_leader_4= "["
endif
if !exists("g:atp_completion_font_encodings")
    let g:atp_completion_font_encodings	= ['T1', 'T2', 'T3', 'T5', 'OT1', 'OT2', 'OT4', 'UT1']
endif
if !exists("g:atp_font_encoding")
    let s:line=atplib#search#SearchPackage('fontenc')
    if s:line != 0
	" the last enconding is the default one for fontenc, this we will
	" use
	let s:enc=matchstr(getline(s:line),'\\usepackage\s*\[\%([^,]*,\)*\zs[^]]*\ze\]\s*{fontenc}')
    else
	let s:enc='OT1'
    endif
    let g:atp_font_encoding=s:enc
    unlet s:line
    unlet s:enc
endif
if !exists("g:atp_no_star_environments")
    let g:atp_no_star_environments=['document', 'flushright', 'flushleft', 'center', 
		\ 'enumerate', 'itemize', 'tikzpicture', 'scope', 
		\ 'picture', 'array', 'proof', 'tabular', 'table' ]
endif
if !exists("g:atp_sizes_of_brackets")
    let g:atp_sizes_of_brackets={'\left': '\right', 
			    \ '\bigl' 	: '\bigr', 
			    \ '\Bigl' 	: '\Bigr', 
			    \ '\biggl' 	: '\biggr' , 
			    \ '\Biggl' 	: '\Biggr', 
			    \ '\big'	: '\big',
			    \ '\Big'	: '\Big',
			    \ '\bigg'	: '\bigg',
			    \ '\Bigg'	: '\Bigg',
			    \ '\' 	: '\',
			    \ }
   " the last one is not a size of a bracket is to a hack to close \(:\), \[:\] and
   " \{:\}
endif
if !exists("g:atp_algorithmic_dict")
    let g:atp_algorithmic_dict = { 'IF' : 'ENDIF', 'FOR' : 'ENDFOR', 'WHILE' : 'ENDWHILE' }
endif
if !exists("g:atp_bracket_dict")
    let g:atp_bracket_dict = { '(' : ')', '{' : '}', '[' : ']', '\lceil' : '\rceil', '\lfloor' : '\rfloor', '\langle' : '\rangle', '\lgroup' : '\rgroup', '<' : '>', '\begin' : '\end' }
endif
if !exists("g:atp_LatexBox")
    let g:atp_LatexBox		= 1
endif
if !exists("g:atp_check_if_LatexBox")
    let g:atp_check_if_LatexBox	= 1
endif
if !exists("g:atp_autex_check_if_closed")
    let g:atp_autex_check_if_closed = 1
endif
if !exists("g:atp_env_maps_old")
    let g:atp_env_maps_old	= 0
endif
if !exists("g:atp_amsmath")
    let g:atp_amsmath=atplib#search#SearchPackage('ams')
endif
if atplib#search#SearchPackage('amsmath') || g:atp_amsmath != 0 || atplib#search#DocumentClass(b:atp_MainFile) =~ '^ams'
    exe "setlocal complete+=k".globpath(&rtp, "ftplugin/ATP_files/dictionaries/ams_dictionary")
endif
if !exists("g:atp_no_math_command_completion")
    let g:atp_no_math_command_completion = 0
endif
if !exists("g:atp_tex_extensions")
    let g:atp_tex_extensions	= ["tex.project.vim", "aux", "_aux", "log", "bbl", "blg", "bcf", "run.xml", "spl", "snm", "nav", "thm", "brf", "out", "toc", "mpx", "idx", "ind", "ilg", "maf", "glo", "mtc[0-9]", "mtc1[0-9]", "pdfsync", "synctex.gz" ]
    if g:atp_ParseLog
	call add(g:atp_tex_extensions, '_log')
    endif
endif
for ext in g:atp_tex_extensions
    let suffixes = split(&suffixes, ",")
    if index(suffixes, ".".ext) == -1 && ext !~ 'mtc'
	exe "setlocal suffixes+=.".ext
    endif
endfor
if !exists("g:atp_delete_output")
    let g:atp_delete_output	= 0
endif
if !exists("g:atp_keep")
    " Files with this extensions will be compied back and forth to/from temporary
    " directory in which compelation happens.
    let g:atp_keep=[ "log", "aux", "toc", "bbl", "ind", "idx", "synctex.gz", "blg", "loa", "toc", "lot", "lof", "thm", "out", "nav" ]
    " biber stuff is added before compelation, this makes it possible to change 
    " to biber on the fly
    if b:atp_BibCompiler =~ '^\s*biber\>'
	let g:atp_keep += [ "run.xml", "bcf" ]
    endif
endif
if !exists("g:atp_ssh")
    " WINDOWS NOT COMPATIBLE
    let g:atp_ssh=$USER . "@localhost"
endif
" opens bibsearch results in vertically split window.
if !exists("g:vertical")
    let g:vertical		= 1
endif
if !exists("g:matchpair")
    let g:matchpair="(:),[:],{:}"
endif
if !exists("g:atp_compare_embedded_comments") || g:atp_compare_embedded_comments != 1
    let g:atp_compare_embedded_comments  = 0
endif
if !exists("g:atp_compare_double_empty_lines") || g:atp_compare_double_empty_lines != 0
    let g:atp_compare_double_empty_lines = 1
endif
"TODO: put toc_window_with and labels_window_width into DOC file
if !exists("g:atp_toc_window_width")
    let g:atp_toc_window_width 	= 30
endif
if !exists("t:toc_window_width")
    let t:toc_window_width	= g:atp_toc_window_width
endif
if !exists("t:atp_labels_window_width")
    if exists("g:labels_window_width")
	let t:atp_labels_window_width = g:labels_window_width
    else
	let t:atp_labels_window_width = 30
    endif
endif
if !exists("g:atp_completion_limits")
    let g:atp_completion_limits	= [40,60,80,120,60]
endif
if !exists("g:atp_long_environments")
    let g:atp_long_environments	= []
endif
if !exists("g:atp_no_complete")
     let g:atp_no_complete	= ['document']
endif
" if !exists("g:atp_close_after_last_closed")
"     let g:atp_close_after_last_closed=1
" endif
if !exists("g:atp_no_env_maps")
    let g:atp_no_env_maps	= 0
endif
if !exists("g:atp_extra_env_maps")
    let g:atp_extra_env_maps	= 0
endif
" todo: to doc. Now they go first.
" if !exists("g:atp_math_commands_first")
"     let g:atp_math_commands_first=1
" endif
if !exists("g:atp_completion_truncate")
    let g:atp_completion_truncate	= 4
endif
" add server call back (then automatically reads errorfiles)
if !exists("g:atp_statusNotif")
    if has('clientserver') && !empty(v:servername) 
	let g:atp_statusNotif	= 1
    else
	let g:atp_statusNotif	= 0
    endif
endif
if !exists("g:atp_statusNotifHi")
    " User<nr>  - highlight status notifications with highlight group User<nr>.
    let g:atp_statusNotifHi	= 0
endif
if !exists("g:atp_callback")
    if exists("g:atp_statusNotif") && g:atp_statusNotif == 1 &&
		\ has('clientserver') && !empty(v:servername)
	let g:atp_callback	= 1
    else
	let g:atp_callback	= 0
    endif
endif
if !exists("g:atp_ProgressBarFile")
    " Only needed if g:atp_callback == 0
    let g:atp_ProgressBarFile = tempname()
endif
" }}}

" PROJECT SETTINGS:
" {{{1
if !exists("g:atp_ProjectLocalVariables")
    " This is a list of variable names which will be preserved in project files
    let g:atp_ProjectLocalVariables = [
		\ "b:atp_MainFile", 	"g:atp_mapNn", 		"b:atp_autex",
		\ "b:atp_TexCompiler", 	"b:atp_TexOptions", 	"b:atp_TexFlavor", 
		\ "b:atp_auruns", 	"b:atp_ReloadOnError",
		\ "b:atp_OpenViewer", 	"b:atp_XpdfServer",
		\ "b:atp_Viewer", 	"b:TreeOfFiles",	"b:ListOfFiles",
		\ "b:TypeDict", 	"b:LevelDict", 		"b:atp_BibCompiler",
		\ "b:atp_StarEnvDefault", 	"b:atp_StarMathEnvDefault",
		\ "b:atp_updatetime_insert", 	"b:atp_updatetime_normal",
		\ ] 
    if !has("python")
	call extend(g:atp_ProjectLocalVariables, ["b:atp_LocalCommands", "b:atp_LocalEnvironments", "b:atp_LocalColors"])
    endif
endif
" This variable is used by atplib#motion#GotoFile (atp-:Edit command):c
let g:atp_SavedProjectLocalVariables = [
		\ "b:atp_MainFile", 	"g:atp_mapNn", 		"b:atp_autex",
		\ "b:atp_TexCompiler", 	"b:atp_TexOptions", 	"b:atp_TexFlavor", 
		\ "b:atp_ProjectDir", 	"b:atp_auruns", 	"b:atp_ReloadOnError",
		\ "b:atp_OutDir",	"b:atp_OpenViewer", 	"b:atp_XpdfServer",
		\ "b:atp_Viewer", 	"b:TreeOfFiles",	"b:ListOfFiles",
		\ "b:TypeDict", 	"b:LevelDict", 		"b:atp_BibCompiler",
		\ "b:atp_StarEnvDefault", 	"b:atp_StarMathEnvDefault",
		\ "b:atp_updatetime_insert", 	"b:atp_updatetime_normal", 
		\ "b:atp_ErrorFormat", 	"b:atp_LastLatexPID",	"b:atp_LatexPIDs",
		\ "b:atp_LatexPIDs",	"b:atp_BibtexPIDs",	"b:atp_MakeindexPIDs",
		\ ]

" }}}1

" This is to be extended into a nice function which shows the important options
" and allows to reconfigure atp
"{{{ ShowOptions
let s:file	= expand('<sfile>:p')
function! s:ShowOptions(bang,...)

    let pattern	= a:0 >= 1 ? a:1 : ".*,"
    let mlen	= max(map(copy(keys(s:optionsDict)), "len(v:val)"))

    redraw
    echohl WarningMsg
    echo "Local buffer variables:"
    echohl None
    for key in sort(keys(s:optionsDict))
	let space = ""
	for s in range(mlen-len(key)+1)
	    let space .= " "
	endfor
	if "b:".key =~ pattern
" 	    if patn != '' && "b:".key !~ patn
		echo "b:".key.space.string(getbufvar(bufnr(""), key))
" 	    endif
	endif
    endfor
    if a:bang == "!"
" 	Show some global options
	echo "\n"
	echohl WarningMsg
	echo "Global variables (defined in ".s:file."):"
	echohl None
	let saved_loclist	= getloclist(0)
	    execute "lvimgrep /^\\s*let\\s\\+g:/j " . fnameescape(s:file)
	let global_vars		= getloclist(0)
	call setloclist(0, saved_loclist)
	let var_list		= []

	for var in global_vars
	    let var_name	= matchstr(var['text'], '^\s*let\s\+\zsg:\S*\ze\s*=')
	    if len(var_name) 
		call add(var_list, var_name)
	    endif
	endfor
	call sort(var_list)

	" Filter only matching variables that exists!
	call filter(var_list, 'count(var_list, v:val) == 1 && exists(v:val)')
	let mlen	= max(map(copy(var_list), "len(v:val)"))
	for var_name in var_list
	    let space = ""
	    for s in range(mlen-len(var_name)+1)
		let space .= " "
	    endfor
	    if var_name =~ pattern && var_name !~ '_command\|_amsfonts\|ams_negations\|tikz_\|keywords'
" 		if patn != '' && var_name !~ patn
		if index(["g:atp_LatexPackages", "g:atp_LatexClasses", "g:atp_completion_modes", "g:atp_completion_modes_normal_mode", "g:atp_Environments", "g:atp_shortname_dict", "g:atp_MathTools_environments", "g:atp_keymaps", "g:atp_CupsOptions", "g:atp_CompilerMsg_Dict", "g:ViewerMsg_Dict", "g:CompilerMsg_Dict", "g:atp_amsmath_environments", "g:atp_siuinits"], var_name) == -1 && var_name !~# '^g:atp_Beamer' && var_name !~# '^g:atp_TodoNotes'
		    echo var_name.space.string({var_name})
		    if len(var_name.space.string({var_name})) > &l:columns
			echo "\n"
		    endif
		endif
" 		endif
	    endif
	endfor

    endif
endfunction
command! -buffer -bang -nargs=* ShowOptions		:call <SID>ShowOptions(<q-bang>, <q-args>)
"}}}
" DEBUG MODE VARIABLES:
" {{{ Debug Mode
let t:atp_DebugMode	= g:atp_DefaultDebugMode 
" there are three possible values of t:atp_DebugMode
" 	silent/normal/debug
if !exists("t:atp_QuickFixOpen")
    let t:atp_QuickFixOpen	= 0
endif

if !s:did_options
    augroup ATP_DebugMode
	au!
	au BufEnter *.tex let t:atp_DebugMode	 = ( exists("t:atp_DebugMode") ? t:atp_DebugMode : g:atp_DefaultDebugMode )
	au BufEnter *.tex let t:atp_QuickFixOpen = ( exists("t:atp_QuickFixOpen") ? t:atp_QuickFixOpen : 0 )
	" When opening the quickfix error buffer:  
	au FileType qf 	let t:atp_QuickFixOpen 	 = 1
	" When closing the quickfix error buffer (:close, :q) also end the Debug Mode.
	au FileType qf 	au BufUnload <buffer> let t:atp_DebugMode = g:atp_DefaultDebugMode | let t:atp_QuickFixOpen = 0
	au FileType qf	setl nospell norelativenumber nonumber
    augroup END
endif
"}}}

" BABEL:
" {{{1 variables
if !exists("g:atp_keymaps")
let g:atp_keymaps = { 
		\ 'british'	: 'ignore',		'english' 	: 'ignore',
		\ 'USenglish'	: 'ignore', 		'UKenglish'	: 'ignore',
		\ 'american'	: 'ignore',
	    	\ 'bulgarian' 	: 'bulgarian-bds', 	'croatian' 	: 'croatian',
		\ 'czech'	: 'czech',		'greek'		: 'greek',
		\ 'plutonikogreek': 'greek',		'hebrew'	: 'hebrew',
		\ 'russian' 	: 'russian-jcuken',	'serbian' 	: 'serbian',
		\ 'slovak' 	: 'slovak', 		'ukrainian' 	: 'ukrainian-jcuken',
		\ 'polish' 	: 'polish-slash' }
else "extend the existing dictionary with default values not ovverriding what is defind:
    for lang in [ 'croatian', 'czech', 'greek', 'hebrew', 'serbian', 'slovak' ] 
	call extend(g:atp_keymaps, { lang : lang }, 'keep')
    endfor
    call extend(g:atp_keymaps, { 'british' 	: 'ignore' }, 		'keep')
    call extend(g:atp_keymaps, { 'american' 	: 'ignore' }, 		'keep')
    call extend(g:atp_keymaps, { 'english' 	: 'ignore' }, 		'keep')
    call extend(g:atp_keymaps, { 'UKenglish' 	: 'ignore' }, 		'keep')
    call extend(g:atp_keymaps, { 'USenglish' 	: 'ignore' }, 		'keep')
    call extend(g:atp_keymaps, { 'bulgarian' 	: 'bulgarian-bds' }, 	'keep')
    call extend(g:atp_keymaps, { 'plutonikogreek' : 'greek' }, 		'keep')
    call extend(g:atp_keymaps, { 'russian' 	: 'russian-jcuken' }, 	'keep')
    call extend(g:atp_keymaps, { 'ukrainian' 	: 'ukrainian-jcuken' },	'keep')
endif

" {{{1 <SID>Babel
function! <SID>Babel()
    " Todo: make notification.
    if &filetype != "tex" || !exists("b:atp_MainFile") || !has("keymap")
	" This only works for LaTeX documents.
	" but it might work for plain tex documents as well!
	return
    endif
    let atp_MainFile	= atplib#FullPath(b:atp_MainFile)

    let saved_loclist = getloclist(0)
    try
	execute '1lvimgrep /^[^%]*\\usepackage.*{babel}/j ' . fnameescape(atp_MainFile)
	" Find \usepackage[babel_options]{babel} - this is the only way that one can
	" pass options to babel.
    catch /E480:/
	return
    catch /E683:/ 
	return
    endtry
    let babel_line 	= get(get(getloclist(0), 0, {}), 'text', '')
    call setloclist(0, saved_loclist) 
    let languages	= split(matchstr(babel_line, '\[\zs[^]]*\ze\]'), ',')
    if len(languages) == 0
	return
    endif
    let default_language 	= get(languages, '-1', '') 
	if g:atp_debugBabel
	    echomsg "[Babel:] defualt language: " . default_language
	endif
    let keymap 			= get(g:atp_keymaps, default_language, '')

    if keymap == ''
	if g:atp_debugBabel
	    echoerr "No keymap in g:atp_keymaps.\n" . babel_line
	endif
	return
    endif

    if keymap != 'ignore'
	execute "set keymap=" . keymap
    else
	execute "set keymap="
    endif
endfunction
command! -buffer Babel	:call <SID>Babel()
" {{{1 start up
if g:atp_babel
    call <SID>Babel()
endif
"  }}}1

" These are two functions which sets options for Xpdf and Xdvi. 
" {{{ Xpdf, Xdvi
" xdvi - supports forward and reverse searching
" {{{ SetXdvi
function! <SID>SetXdvi()

    if buflisted(atplib#FullPath(b:atp_MainFile))
	let line = getbufline(atplib#FullPath(b:atp_MainFile), 1)[0]
	if line =~ '^%&\w*tex\>'
	    let compiler = matchstr(line, '^%&\zs\w\+')
	else
	    let compiler = ""
	endif
    else
	let line = readfile(atplib#FullPath(b:atp_MainFile))[0] 
	if line =~ '^%&\w*tex\>'
	    let compiler = matchstr(line, '^%&\zs\w\+')
	else
	    let compiler = ""
	endif
    endif
    if compiler != "" && compiler !~ '\(la\)\=tex'
	echohl Error
	echomsg "[SetXdvi:] You need to change the first line of your project!"
	echohl None
    endif

    " Remove menu entries
    let Compiler		= get(g:CompilerMsg_Dict, matchstr(b:atp_TexCompiler, '^\s*\S*'), 'Compiler')
    let Viewer			= get(g:ViewerMsg_Dict, matchstr(b:atp_Viewer, '^\s*\S*'), 'View\ Output')
    try
	execute "aunmenu LaTeX.".Compiler
	execute "aunmenu LaTeX.".Compiler."\\ debug"
	execute "aunmenu LaTeX.".Compiler."\\ twice"
	execute "aunmenu LaTeX.View\\ with\\ ".Viewer
    catch /E329:/
    endtry

    " Set new options:
    let b:atp_TexCompiler	= "latex"
    let b:atp_TexOptions	= "-src-specials"
    let b:atp_Viewer		= "xdvi"
    if exists("g:atp_xdviOptions")
	let g:atp_xdviOptions	+= index(g:atp_xdviOptions, '-editor') != -1 && 
		    \ ( !exists("b:atp_xdviOptions") || exists("b:atp_xdviOptions") && index(b:atp_xdviOptions,  '-editor') != -1 )
		    \ ? ["-editor", v:progname." --servername ".v:servername." --remote-wait +%l %f"] : []
	if index(g:atp_xdviOptions, '-watchfile') != -1 && 
	\ ( !exists("b:atp_xdviOptions") || exists("b:atp_xdviOptions") && index(b:atp_xdviOptions,  '-watchfile') != -1 )
	    let g:atp_xdviOptions += [ '-watchfile', '1' ]
	endif

    else
	if ( !exists("b:atp_xdviOptions") || exists("b:atp_xdviOptions") && index(b:atp_xdviOptions,  '-editor') != -1 )
	    let g:atp_xdviOptions = ["-editor",  v:progname." --servername ".v:servername." --remote-wait +%l %f"]
	endif
	if ( !exists("b:atp_xdviOptions") || exists("b:atp_xdviOptions") && index(b:atp_xdviOptions,  '-watchfile') != -1 )
	    if exists("g:atp_xdviOptions")
		let g:atp_xdviOptions += [ '-watchfile', '1' ]
	    else
		let g:atp_xdviOptions = [ '-watchfile', '1' ]
	    endif
	endif
    endif

    map <buffer> <LocalLeader>rs				:call RevSearch()<CR>
    try
	nmenu 550.65 &LaTeX.Reverse\ Search<Tab>:map\ <LocalLeader>rs	:RevSearch<CR>
    catch /E329:/
    endtry

    " Put new menu entries:
    let Compiler	= get(g:CompilerMsg_Dict, matchstr(b:atp_TexCompiler, '^\s*\zs\S*'), 'Compile')
    let Viewer		= get(g:ViewerMsg_Dict, matchstr(b:atp_Viewer, '^\s*\zs\S*'), "View\\ Output")
    execute "nmenu 550.5 &Latex.&".Compiler."<Tab>:TEX			:TEX<CR>"
    execute "nmenu 550.6 &Latex.".Compiler."\\ debug<Tab>:TEX\\ debug 	:DTEX<CR>"
    execute "nmenu 550.7 &Latex.".Compiler."\\ &twice<Tab>:2TEX		:2TEX<CR>"
    execute "nmenu 550.10 Latex.&View\\ with\\ ".Viewer."<Tab>:ViewOutput 		:ViewOutput<CR>"
endfunction
command! -buffer SetXdvi			:call <SID>SetXdvi()
nnoremap <silent> <buffer> <Plug>SetXdvi	:call <SID>SetXdvi()<CR>
" }}}

" xpdf - supports server option (we use the reoding mechanism, which allows to
" copy the output file but not reload the viewer if there were errors during
" compilation (b:atp_ReloadOnError variable)
" {{{ SetXpdf
function! <SID>SetPdf(viewer)

    " Remove menu entries.
    let Compiler		= get(g:CompilerMsg_Dict, matchstr(b:atp_TexCompiler, '^\s*\S*'), 'Compiler')
    let Viewer			= get(g:ViewerMsg_Dict, matchstr(b:atp_Viewer, '^\s*\S*'), 'View\ Output')
    try 
	execute "aunmenu Latex.".Compiler
	execute "aunmenu Latex.".Compiler."\\ debug"
	execute "aunmenu Latex.".Compiler."\\ twice"
	execute "aunmenu Latex.View\\ with\\ ".Viewer
    catch /E329:/
    endtry

    if buflisted(atplib#FullPath(b:atp_MainFile))
	let line = getbufline(atplib#FullPath(b:atp_MainFile), 1)[0]
	if line =~ '^%&\w*tex>'
	    let compiler = matchstr(line, '^%&\zs\w\+')
	else
	    let compiler = ""
	endif
    else
	let line = readfile(atplib#FullPath(b:atp_MainFile))[0] 
	if line =~ '^%&\w*tex\>'
	    let compiler = matchstr(line, '^%&\zs\w\+')
	else
	    let compiler = ""
	endif
    endif
    if compiler != "" && compiler !~ 'pdf\(la\)\=tex'
	echohl Error
	echomsg "[SetPdf:] You need to change the first line of your project!"
	echohl None
    endif

    let b:atp_TexCompiler	= "pdflatex"
    " We have to clear tex options (for example -src-specials set by :SetXdvi)
    let b:atp_TexOptions	= "-synctex=1"
    let preview_viewer		= b:atp_Viewer
    let b:atp_Viewer		= a:viewer

    if has("unix") && has("clientserver")
	if a:viewer ==? 'evince'
	    let input_path  = atplib#FullPath(b:atp_MainFile)
	    let output_path = fnamemodify(input_path, ":r").".pdf"
	    " Start sync script
	    let sync_cmd = g:atp_Python." ".shellescape(split(globpath(&rtp, "ftplugin/ATP_files/evince_sync.py"), "\n")[0])
			\ ." ".toupper(v:progname)." ".shellescape(v:servername)
			\ ." ".shellescape(output_path)
			\ ." ".shellescape(input_path)
			\ ." &"
	    call system(sync_cmd)
	elseif preview_viewer ==? 'evince'
	    " Stop sync script.
            call <SID>Kill_Evince_Sync()
	endif
    endif

    " Delete menu entry.
    try
	silent aunmenu Latex.Reverse\ Search
    catch /E329:/
    endtry

    " Put new menu entries:
    let Compiler	= get(g:CompilerMsg_Dict, matchstr(b:atp_TexCompiler, '^\s*\zs\S*'), 'Compile')
    let Viewer		= get(g:ViewerMsg_Dict, matchstr(b:atp_Viewer, '^\s*\zs\S*'), 'View\ Output')
    execute "nmenu 550.5 &Latex.&".Compiler.	"<Tab>:TEX			:TEX<CR>"
    execute "nmenu 550.6 &Latex." .Compiler.	"\\ debug<Tab>:TEX\\ debug 	:DTEX<CR>"
    execute "nmenu 550.7 &Latex." .Compiler.	"\\ &twice<Tab>:2TEX		:2TEX<CR>"
    execute "nmenu 550.10 Latex.&View\\ with\\ ".Viewer.	"<Tab>:ViewOutput 		:ViewOutput<CR>"
endfunction
command! -buffer SetXpdf			:call <SID>SetPdf('xpdf')
command! -buffer SetOkular			:call <SID>SetPdf('okular')
command! -buffer SetEvince			:call <SID>SetPdf('evince')
nnoremap <silent> <buffer> <Plug>SetXpdf	:call <SID>SetPdf('xpdf')<CR>
nnoremap <silent> <buffer> <Plug>SetOkular	:call <SID>SetPdf('okular')<CR>
nnoremap <silent> <buffer> <Plug>SetEvince	:call <SID>SetPdf('evince')<CR>

function! <SID>Kill_Evince_Sync()
python << EOF
try:
    import psutil, vim, os, signal
    from psutil import NoSuchProcess
    for pid in psutil.get_pid_list():
        try:
            process = psutil.Process(pid)
            cmdline = process.cmdline
            if len(cmdline) > 1 and re.search('evince_sync\.py$', cmdline[1]):
                os.kill(pid, signal.SIGTERM)
        except psutil.error.NoSuchProcess:
            pass
        except psutil.error.AccessDenied:
            pass
except ImportError:
    vim.command("echomsg '[ATP:] Import error. You will have to kill evince_sync.py script yourself'")
EOF
endfunction
if has("unix")
    augroup ATP_Evince_Sync
        au!
        au VimLeave * :call <SID>Kill_Evince_Sync()
    augroup END
endif

" }}}
""
" }}}

" These are functions which toggles some of the options:
"{{{ Toggle Functions
if !s:did_options || g:atp_reload_functions
" {{{ ATP_ToggleAuTeX
" command! -buffer -count=1 TEX	:call TEX(<count>)		 
function! ATP_ToggleAuTeX(...)
    if a:0 && ( a:1 == 2 || a:1 == "local" )
	let b:atp_autex=2
	echo "[ATP:] LOCAL"
	silent! aunmenu Latex.Toggle\ AuTeX\ [off]
	silent! aunmenu Latex.Toggle\ AuTeX\ [on]
	silent! aunmenu Latex.Toggle\ AuTeX\ [local]
	menu 550.75 &Latex.&Toggle\ AuTeX\ [local]<Tab>b:atp_autex	:<C-U>ToggleAuTeX<CR>
	cmenu 550.75 &Latex.&Toggle\ AuTeX\ [local]<Tab>b:atp_autex	<C-U>ToggleAuTeX<CR>
	imenu 550.75 &Latex.&Toggle\ AuTeX\ [local]<Tab>b:atp_autex	<ESC>:ToggleAuTeX<CR>a
	return
    endif
    let on = ( a:0 ? ( a:1 == 'on' ? 1 : 0 ) : !b:atp_autex )
    if on
	let b:atp_autex=1	
	echo "[ATP:] ON"
	silent! aunmenu Latex.Toggle\ AuTeX\ [off]
	silent! aunmenu Latex.Toggle\ AuTeX\ [on]
	silent! aunmenu Latex.Toggle\ AuTeX\ [local]
	menu 550.75 &Latex.&Toggle\ AuTeX\ [on]<Tab>b:atp_autex		:<C-U>ToggleAuTeX<CR>
	cmenu 550.75 &Latex.&Toggle\ AuTeX\ [on]<Tab>b:atp_autex	<C-U>ToggleAuTeX<CR>
	imenu 550.75 &Latex.&Toggle\ AuTeX\ [on]<Tab>b:atp_autex	<ESC>:ToggleAuTeX<CR>a
    else
	let b:atp_autex=0
	silent! aunmenu Latex.Toggle\ AuTeX\ [off]
	silent! aunmenu Latex.Toggle\ AuTeX\ [on]
	silent! aunmenu Latex.Toggle\ AuTeX\ [local]
	menu 550.75 &Latex.&Toggle\ AuTeX\ [off]<Tab>b:atp_autex	:<C-U>ToggleAuTeX<CR>
	cmenu 550.75 &Latex.&Toggle\ AuTeX\ [off]<Tab>b:atp_autex	<C-U>ToggleAuTeX<CR>
	imenu 550.75 &Latex.&Toggle\ AuTeX\ [off]<Tab>b:atp_autex	<ESC>:ToggleAuTeX<CR>a
	echo "[ATP:] OFF"
    endif
endfunction
"}}}
" {{{ ATP_ToggleSpace
" Special Space for Searching 
let s:special_space="[off]"
function! ATP_ToggleSpace(...)
    let on	= ( a:0 >=1 ? ( a:1 == 'on'  ? 1 : 0 ) : !g:atp_cmap_space )
    if on
	if mapcheck("<space>", 'c') == ""
	    if &cpoptions =~# 'B'
		cmap <buffer> <expr> <space> 	( g:atp_cmap_space && getcmdtype() =~ '[\/?]' ? '\_s\+' : ' ' )
	    else
		cmap <buffer> <expr> <space> 	( g:atp_cmap_space && getcmdtype() =~ '[\\/?]' ? '\\_s\\+' : ' ' )
	    endif
	endif
	let g:atp_cmap_space=1
	let s:special_space="[on]"
	silent! aunmenu Latex.Toggle\ Space\ [off]
	silent! aunmenu Latex.Toggle\ Space\ [on]
	menu 550.78 &Latex.&Toggle\ Space\ [on]<Tab>cmap\ <space>\ \\_s\\+	:<C-U>ToggleSpace<CR>
	cmenu 550.78 &Latex.&Toggle\ Space\ [on]<Tab>cmap\ <space>\ \\_s\\+	<C-U>ToggleSpace<CR>
	imenu 550.78 &Latex.&Toggle\ Space\ [on]<Tab>cmap\ <space>\ \\_s\\+	<Esc>:ToggleSpace<CR>a
	tmenu &Latex.&Toggle\ Space\ [on] cmap <space> \_s\+ is curently on
	redraw
	let msg = "[ATP:] special space is on"
    else
	let g:atp_cmap_space=0
	let s:special_space="[off]"
	silent! aunmenu Latex.Toggle\ Space\ [on]
	silent! aunmenu Latex.Toggle\ Space\ [off]
	menu 550.78 &Latex.&Toggle\ Space\ [off]<Tab>cmap\ <space>\ \\_s\\+	:<C-U>ToggleSpace<CR>
	cmenu 550.78 &Latex.&Toggle\ Space\ [off]<Tab>cmap\ <space>\ \\_s\\+	<C-U>ToggleSpace<CR>
	imenu 550.78 &Latex.&Toggle\ Space\ [off]<Tab>cmap\ <space>\ \\_s\\+	<Esc>:ToggleSpace<CR>a
	tmenu &Latex.&Toggle\ Space\ [off] cmap <space> \_s\+ is curently off
	redraw
	let msg = "[ATP:] special space is off"
    endif
    return msg
endfunction
" nnoremap <buffer> <silent> <Plug>ToggleSpace	:call ATP_ToggleSpace() 
" cnoremap <buffer> <Plug>ToggleSpace	:call ATP_ToggleSpace() 
function! ATP_CmdwinToggleSpace(on)
    let on		= ( a:0 >=1 ? ( a:1 == 'on'  ? 1 : 0 ) : maparg('<space>', 'i') == "" )
    if on
	echomsg "space ON"
	let backslash 	= ( &l:cpoptions =~# "B" ? "\\" : "\\\\\\" ) 
	exe "imap <space> ".backslash."_s".backslash."+"
    else
	echomsg "space OFF"
	iunmap <space>
    endif
endfunction
"}}}
" {{{ ATP_ToggleCheckMathOpened
" This function toggles if ATP is checking if editing a math mode.
" This is used by insert completion.
" ToDo: to doc.
function! ATP_ToggleCheckMathOpened(...)
    let on	= ( a:0 >=1 ? ( a:1 == 'on'  ? 1 : 0 ) :  !g:atp_MathOpened )
"     if g:atp_MathOpened
    if !on
	let g:atp_MathOpened = 0
	echomsg "[ATP:] check if in math environment is off"
	silent! aunmenu Latex.Toggle\ Check\ if\ in\ Math\ [on]
	silent! aunmenu Latex.Toggle\ Check\ if\ in\ Math\ [off]
	menu 550.79 &Latex.Toggle\ &Check\ if\ in\ Math\ [off]<Tab>g:atp_MathOpened			
		    \ :<C-U>ToggleCheckMathOpened<CR>
	cmenu 550.79 &Latex.Toggle\ &Check\ if\ in\ Math\ [off]<Tab>g:atp_MathOpened			
		    \ <C-U>ToggleCheckMathOpened<CR>
	imenu 550.79 &Latex.Toggle\ &Check\ if\ in\ Math\ [off]<Tab>g:atp_MathOpened			
		    \ <Esc>:ToggleCheckMathOpened<CR>a
    else
	let g:atp_MathOpened = 1
	echomsg "[ATP:] check if in math environment is on"
	silent! aunmenu Latex.Toggle\ Check\ if\ in\ Math\ [off]
	silent! aunmenu Latex.Toggle\ Check\ if\ in\ Math\ [off]
	menu 550.79 &Latex.Toggle\ &Check\ if\ in\ Math\ [on]<Tab>g:atp_MathOpened
		    \ :<C-U>ToggleCheckMathOpened<CR>
	cmenu 550.79 &Latex.Toggle\ &Check\ if\ in\ Math\ [on]<Tab>g:atp_MathOpened
		    \ <C-U>ToggleCheckMathOpened<CR>
	imenu 550.79 &Latex.Toggle\ &Check\ if\ in\ Math\ [on]<Tab>g:atp_MathOpened
		    \ <Esc>:ToggleCheckMathOpened<CR>a
    endif
endfunction
"}}}
" {{{ ATP_ToggleCallBack
function! ATP_ToggleCallBack(...)
    let on	= ( a:0 >=1 ? ( a:1 == 'on'  ? 1 : 0 ) :  !g:atp_callback )
    if !on
	let g:atp_callback	= 0
	echomsg "[ATP:] call back is off"
	silent! aunmenu Latex.Toggle\ Call\ Back\ [on]
	silent! aunmenu Latex.Toggle\ Call\ Back\ [off]
	menu 550.80 &Latex.Toggle\ &Call\ Back\ [off]<Tab>g:atp_callback	
		    \ :<C-U>call ToggleCallBack()<CR>
	cmenu 550.80 &Latex.Toggle\ &Call\ Back\ [off]<Tab>g:atp_callback	
		    \ <C-U>call ToggleCallBack()<CR>
	imenu 550.80 &Latex.Toggle\ &Call\ Back\ [off]<Tab>g:atp_callback	
		    \ <Esc>:call ToggleCallBack()<CR>a
    else
	let g:atp_callback	= 1
	echomsg "[ATP:] call back is on"
	silent! aunmenu Latex.Toggle\ Call\ Back\ [on]
	silent! aunmenu Latex.Toggle\ Call\ Back\ [off]
	menu 550.80 &Latex.Toggle\ &Call\ Back\ [on]<Tab>g:atp_callback
		    \ :call ToggleCallBack()<CR>
	cmenu 550.80 &Latex.Toggle\ &Call\ Back\ [on]<Tab>g:atp_callback
		    \ <C-U>call ToggleCallBack()<CR>
	imenu 550.80 &Latex.Toggle\ &Call\ Back\ [on]<Tab>g:atp_callback
		    \ <Esc>:call ToggleCallBack()<CR>a
    endif
endfunction
"}}}
" {{{ ATP_ToggleDebugMode
" ToDo: to doc.
" TODO: it would be nice to have this command (and the map) in quickflist (FileType qf)
" describe DEBUG MODE in doc properly.
function! ATP_ToggleDebugMode(mode,...)
    if a:mode != ""
	let set_new 		= 1
	let new_debugmode 	= ( t:atp_DebugMode ==# a:mode ? g:atp_DefaultDebugMode : a:mode )
	let copen 		= ( a:mode =~? '^d\%[ebug]' && t:atp_DebugMode !=? 'debug' && !t:atp_QuickFixOpen )
	let on 			= ( a:mode !=# t:atp_DebugMode )
	if t:atp_DebugMode ==# 'Debug' && a:mode ==# 'debug' || t:atp_DebugMode ==# 'debug' && a:mode ==# 'Debug'
	    let change_menu 	= 0
	else
	    let change_menu 	= 1
	endif
    else
	let change_menu 	= 1
	let new_debugmode	= ""
	if a:0 >= 1 && a:1 =~ '^on\|off$'
	    let [ on, new_debugmode ]	= ( a:1 == 'on'  ? [ 1, 'debug' ] : [0, g:atp_DefaultDebugMode] )
	    let set_new=1
	    let copen = 1
	elseif a:0 >= 1
	    let t:atp_DebugMode	= a:1
	    let new_debugmode 	= a:1
	    let set_new		= 0
	    if a:1 =~ 's\%[ilent]'
		let on		= 0
		let copen		= 0
	    elseif a:1 =~ '^d\%[ebug]'
		let on		= 1 
		let copen		= ( a:1 =~# '^D\%[ebug]' ? 1 : 0 )
	    else
		" for verbose mode
		let on		= 0
		let copen		= 0
	    endif
	else
	    let set_new = 1
	    let [ on, new_debugmode ] = ( t:atp_DebugMode =~? '^\%(debug\|verbose\)$' ? [ 0, g:atp_DefaultDebugMode ] : [ 1, 'debug' ] )
	    let copen 		= 1
	endif
    endif

"     let g:on = on
"     let g:set_new = set_new
"     let g:new_debugmode = new_debugmode
"     let g:copen = copen
"     let g:change_menu = change_menu

    " on == 0 set debug off
    " on == 1 set debug on
    if !on
	echomsg "[ATP debug mode:] ".new_debugmode

	if change_menu
	    silent! aunmenu 550.20.5 Latex.Log.Toggle\ &Debug\ Mode\ [on]
	    silent! aunmenu 550.20.5 Latex.Log.Toggle\ &Debug\ Mode\ [off]
	    menu 550.20.5 &Latex.&Log.Toggle\ &Debug\ Mode\ [off]<Tab>ToggleDebugMode
			\ :<C-U>ToggleDebugMode<CR>
	    cmenu 550.20.5 &Latex.&Log.Toggle\ &Debug\ Mode\ [off]<Tab>ToggleDebugMode
			\ <C-U>ToggleDebugMode<CR>
	    imenu 550.20.5 &Latex.&Log.Toggle\ &Debug\ Mode\ [off]<Tab>ToggleDebugMode
			\ <Esc>:ToggleDebugMode<CR>a

	    silent! aunmenu Latex.Toggle\ Call\ Back\ [on]
	    silent! aunmenu Latex.Toggle\ Call\ Back\ [off]
	    menu 550.80 &Latex.Toggle\ &Call\ Back\ [off]<Tab>g:atp_callback	
			\ :<C-U>ToggleDebugMode<CR>
	    cmenu 550.80 &Latex.Toggle\ &Call\ Back\ [off]<Tab>g:atp_callback	
			\ <C-U>ToggleDebugMode<CR>
	    imenu 550.80 &Latex.Toggle\ &Call\ Back\ [off]<Tab>g:atp_callback	
			\ <Esc>:ToggleDebugMode<CR>a
	endif

	if set_new
	    let t:atp_DebugMode	= new_debugmode
	endif
	silent cclose
    else
	echomsg "[ATP debug mode:] ".new_debugmode

	if change_menu
	    silent! aunmenu 550.20.5 Latex.Log.Toggle\ Debug\ Mode\ [off]
	    silent! aunmenu 550.20.5 Latex.Log.Toggle\ &Debug\ Mode\ [on]
	    menu 550.20.5 &Latex.&Log.Toggle\ &Debug\ Mode\ [on]<Tab>ToggleDebugMode
			\ :<C-U>ToggleDebugMode<CR>
	    cmenu 550.20.5 &Latex.&Log.Toggle\ &Debug\ Mode\ [on]<Tab>ToggleDebugMode
			\ <C-U>ToggleDebugMode<CR>
	    imenu 550.20.5 &Latex.&Log.Toggle\ &Debug\ Mode\ [on]<Tab>ToggleDebugMode
			\ <Esc>:ToggleDebugMode<CR>a

	    silent! aunmenu Latex.Toggle\ Call\ Back\ [on]
	    silent! aunmenu Latex.Toggle\ Call\ Back\ [off]
	    menu 550.80 &Latex.Toggle\ &Call\ Back\ [on]<Tab>g:atp_callback	
			\ :<C-U>ToggleDebugMode<CR>
	    cmenu 550.80 &Latex.Toggle\ &Call\ Back\ [on]<Tab>g:atp_callback	
			\ <C-U>ToggleDebugMode<CR>
	    imenu 550.80 &Latex.Toggle\ &Call\ Back\ [on]<Tab>g:atp_callback	
			\ <Esc>:ToggleDebugMode<CR>a
	endif

	let g:atp_callback	= 1
	if set_new
	    let t:atp_DebugMode	= new_debugmode
	endif
	let winnr = bufwinnr("%")
	if copen
	    let efm=b:atp_ErrorFormat
	    exe "ErrorFormat ".efm
	    silent! cg
	    if len(getqflist()) > 0
		exe "silent copen ".min([atplib#qflength(), g:atp_DebugModeQuickFixHeight])
		exe winnr . " wincmd w"
	    else
		echo "[ATP:] no errors for b:atp_ErrorFormat=".efm
	    endif
	endif
    endif
endfunction
function! ToggleDebugModeCompl(A,B,C)
    return "silent\ndebug\nDebug\nverbose\non\noff"
endfunction
augroup ATP_DebugModeCommandsAndMaps
    au!
    au FileType qf command! -buffer ToggleDebugMode 	:call <SID>ToggleDebugMode()
    au FileType qf nnoremap <silent> <LocalLeader>D		:ToggleDebugMode<CR>
augroup END
" }}}
" {{{ ATP_ToggleTab
" switches on/off the <Tab> map for TabCompletion
function! ATP_ToggleTab(...)
    if mapcheck('<F7>','i') !~ 'atplib#complete#TabCompletion'
	let on	= ( a:0 >=1 ? ( a:1 == 'on'  ? 1 : 0 ) : mapcheck('<Tab>','i') !~# 'atplib#complete#TabCompletion' )
	if !on 
	    iunmap <buffer> <Tab>
	    echo '[ATP:] <Tab> map OFF'
	else
	    imap <buffer> <Tab> <C-R>=atplib#complete#TabCompletion(1)<CR>
	    echo '[ATP:] <Tab> map ON'
	endif
    endif
endfunction
" }}}
" {{{ ATP_ToggleIMaps
" switches on/off the imaps g:atp_imap_math, g:atp_imap_math_misc and
" g:atp_imap_diacritics
function! ATP_ToggleIMaps(insert_enter, bang,...)
    let on	= ( a:0 >=1 ? ( a:1 == 'on'  ? 1 : 0 ) : g:atp_imap_define_math <= 0 || g:atp_imap_define_math_misc <= 0 )
    if on == 0
	let g:atp_imap_define_math = ( a:bang == "!" ? -1 : 0 ) 
	call atplib#DelMaps(g:atp_imap_math)
	let g:atp_imap_define_math_misc = ( a:bang == "!" ? -1 : 0 )
	call atplib#DelMaps(g:atp_imap_math_misc)
	let g:atp_imap_define_diacritics = ( a:bang == "!" ? -1 : 0 ) 
	call atplib#DelMaps(g:atp_imap_diacritics)
	echo '[ATP:] imaps OFF '.(a:bang == "" ? '(insert)' : '')
    else
	let g:atp_imap_define_math =1
	let g:atp_imap_define_math_misc = 1
	let g:atp_imap_define_diacritics = 1
	if atplib#IsInMath()
	    call atplib#MakeMaps(g:atp_imap_math)
	    call atplib#MakeMaps(g:atp_imap_math_misc)
	else
	    call atplib#MakeMaps(g:atp_imap_diacritics)
	endif
	echo '[ATP:] imaps ON'
    endif
" Setting eventignore is not a good idea 
" (this might break specific user settings)
"     if a:insert_enter
" 	let g:atp_eventignore=&l:eventignore
" 	let g:atp_eventignoreInsertEnter=1
" 	set eventignore+=InsertEnter
" " 	" This doesn't work because startinsert runs after function ends.
"     endif
endfunction
" }}}
endif
" }}}
 
" Some Commands And Maps:
"{{{
command! -buffer ToggleSpace	:call <SID>ToggleSpace()
command! -buffer -nargs=? -complete=customlist,atplib#OnOffComp	ToggleIMaps	 	:call ATP_ToggleIMaps(0, "!", <f-args>)
nnoremap <silent> <buffer> 	<Plug>ToggleIMaps		:call ATP_ToggleIMaps(0, "!")<CR>
inoremap <silent> <buffer> 	<Plug>ToggleIMaps		<C-O>:call ATP_ToggleIMaps(0, "!")<CR>
" inoremap <silent> <buffer> 	<Plug>ToggleIMaps		<Esc>:call ATP_ToggleIMaps(1, "")<CR>

command! -buffer -nargs=? -complete=customlist,atplib#OnOffLocalComp ToggleAuTeX 	:call ATP_ToggleAuTeX(<f-args>)
nnoremap <silent> <buffer> 	<Plug>ToggleAuTeX 		:call ATP_ToggleAuTeX()<CR>

command! -buffer -nargs=? -complete=customlist,atplib#OnOffComp ToggleSpace 	:echo ATP_ToggleSpace(<f-args>)
nnoremap <silent> <buffer> 	<Plug>ToggleSpace 		:echo ATP_ToggleSpace()<CR>
nnoremap <silent> <buffer> 	<Plug>ToggleSpaceOn 		:echo ATP_ToggleSpace('on')<CR>
nnoremap <silent> <buffer> 	<Plug>ToggleSpaceOff 		:echo ATP_ToggleSpace('off')<CR>

command! -buffer -nargs=? -complete=customlist,atplib#OnOffComp	ToggleCheckMathOpened 	:call ATP_ToggleCheckMathOpened(<f-args>)
nnoremap <silent> <buffer> 	<Plug>ToggleCheckMathOpened	:call ATP_ToggleCheckMathOpened()<CR>

command! -buffer -nargs=? -complete=customlist,atplib#OnOffComp	ToggleCallBack 		:call ATP_ToggleCallBack(<f-args>)
nnoremap <silent> <buffer> 	<Plug>ToggleCallBack		:call ATP_ToggleCallBack()<CR>

command! -buffer -nargs=? -complete=custom,ToggleDebugModeCompl	ToggleDebugMode 	:call ATP_ToggleDebugMode("",<f-args>)
nnoremap <silent> <buffer> 	<Plug>TogglesilentMode		:call ATP_ToggleDebugMode("silent")<CR>
nnoremap <silent> <buffer> 	<Plug>ToggledebugMode		:call ATP_ToggleDebugMode("debug")<CR>
nnoremap <silent> <buffer> 	<Plug>ToggleDebugMode		:call ATP_ToggleDebugMode("Debug")<CR>

if g:atp_tab_map
    command! -buffer -nargs=? -complete=customlist,atplib#OnOffComp	ToggleTab	 	:call ATP_ToggleTab(<f-args>)
endif
nnoremap <silent> <buffer> 	<Plug>ToggleTab		:call ATP_ToggleTab()<CR>
inoremap <silent> <buffer> 	<Plug>ToggleTab		<C-O>:call ATP_ToggleTab()<CR>
"}}}

" Read Package/Documentclass Files {{{
" This is run by an autocommand group ATP_Packages which is after ATP_LocalCommands
" b:atp_LocalColors are used in some package files.
function! <SID>ReadPackageFiles()
    let time=reltime()
    let package_files = split(globpath(&rtp, "ftplugin/ATP_files/packages/*"), "\n")
    let g:atp_packages = map(copy(package_files), 'fnamemodify(v:val, ":t:r")')
    for file in package_files
	" We cannot restrict here to not source some files - because the completion
	" variables might be needed later. I need to find another way of using this files
	" as additional scripts running syntax ... commands for example only if the
	" packages are defined.
	execute "source ".file
    endfor
    let g:source_time_package_files=reltimestr(reltime(time))
endfunction

" }}}

" AUTOCOMMANDS:
" Some of the autocommands (Status Line, LocalCommands, Log File):
" {{{ Autocommands:

if !s:did_options
    

    let g:atp_DoSwapExists = 0
    fun! <SID>SwapExists(swapfile)
	if g:atp_DoSwapExists
	    let v:swapchoice = 'a'
	    echoerr "[ATP:] swap exist for file ".a:swapfile
	else
	    let v:swapchoice = ''
	endif
    endfun

"     augroup ATP_SwapExists
" 	au!
" 	au SwapExists	:call <SID>SwapExists(v:swapname)
"     augroup END
    augroup ATP_changedtick
	au!
	au BufEnter,BufWritePost 	*.tex 	:let b:atp_changedtick = b:changedtick
    augroup END 

    augroup ATP_auTeX
	au!
	au CursorHold 	*.tex call atplib#compiler#auTeX()
	au CursorHoldI 	*.tex call atplib#compiler#auTeX()
    augroup END 
    " {{{ Setting ErrorFormat
    " Is done using autocommands, if the opened file belongs to the same
    " project as the previous file, then just copy the variables
    " b:atp_ErrorFormat, other wise read the error file and set error format
    " to g:atp_DefaultErrorFormat (done with
    " atplib#compiler#SetErrorFormat()).
    "
    " Todo: still :copen changes &efm to sth from tex.vim.
    "
    " For sty and cls files, always pretend they belong to the same project.
    function! ATP_BufLeave()
	let s:error_format = ( exists("b:atp_ErrorFormat") ? b:atp_ErrorFormat : 'no_error_format' )
	let s:ef = &l:ef
" 	echomsg "PFILE ".s:previous_file." EFM ".s:error_format
    endfunction
    let s:error_format = ( exists("b:atp_ErrorFormat") ? b:atp_ErrorFormat : 'no_error_format' )
    let s:ef = &l:ef
    function! <SID>BufEnter()
	if !( &l:filetype == 'tex' || &l:ef == s:ef  )
	    " buftype option is not yet set when this function is executed,
	    " but errorfile option is already set.
" 	    echomsg "FILETYPE RETURN"
	    return
	endif
" 	if exists("s:previous_file")
	if exists("s:ef")
	    let same_project= ( &l:ef == s:ef )
	    if !same_project
" 		echomsg "OTHER PROJECT ".g:atp_DefaultErrorFormat . " " . expand("%:p")
		let errorflags = exists("b:atp_ErrorFormat") ? b:atp_ErrorFormat : g:atp_DefaultErrorFormat
		call atplib#compiler#SetErrorFormat(1, errorflags)
	    else
" 		echomsg "SAME PROJECT ".s:error_format . " " . expand("%:p")
		if s:error_format != 'no_error_format'
		    call atplib#compiler#SetErrorFormat(0, s:error_format)
		else
		    call atplib#compiler#SetErrorFormat(0, g:atp_DefaultErrorFormat)
		endif
	    endif
	else
" 	    echomsg "INIT ".g:atp_DefaultErrorFormat . " " . expand("%:p")
	    call atplib#compiler#SetErrorFormat(1, g:atp_DefaultErrorFormat)
	    let &efm=&l:efm
	endif
    endfunction

" This augroup sets the efm on startup:
    augroup ATP_ErrorFormat
	au!
	au BufLeave * :call ATP_BufLeave()
	au BufEnter * :call <SID>BufEnter()
    augroup END
    "}}}

    augroup ATP_UpdateToCLine
	au!
	au CursorHold *.tex nested :call atplib#motion#UpdateToCLine()
    augroup END

    function! RedrawToC()
	if bufwinnr(bufnr("__ToC__")) != -1
	    let winnr = winnr()
	    TOC
	    exe winnr." wincmd w"
	endif
    endfunction

    augroup ATP_TOC_tab
	au!
	au TabEnter *.tex	:call RedrawToC()
    augroup END

    let g:atp_eventignore		= &l:eventignore
    let g:atp_eventignoreInsertEnter 	= 0
    function! <SID>InsertLeave_InsertEnter()
	if g:atp_eventignoreInsertEnter
	    setl eventignore-=g:atp_eventignore
	endif
    endfunction
    augroup ATP_InsertLeave_eventignore
	" ToggleMathIMaps
	au!
	au InsertLeave *.tex 	:call <SID>InsertLeave_InsertEnter()
    augroup END

"     augroup ATP_Cmdwin
" 	au!
" 	au CmdwinLeave / if expand("<afile>") == "/"|:call ATP_CmdwinToggleSpace(0)|:endif
" 	au CmdwinLeave ? if expand("<afile>") == "/"|:call ATP_CmdwinToggleSpace(0)|:endif
"     augroup END

    augroup ATP_cmdheight
	" update g:atp_cmdheight when user writes the buffer
	au!
	au BufWrite *.tex :let g:atp_cmdheight = &l:cmdheight
    augroup END

function! <SID>Rmdir(dir)
if executable("rmdir")
    call system("rmdir ".shellescape(a:dir))
elseif has("python")
python << EOF
import shutil, errno
dir=vim.eval('a:dir')
try:
    shutil.rmtree(dir)
except OSError, e:
    if errno.errorcode[e.errno] == 'ENOENT':
        pass
EOF
else
    echohl ErrorMsg
    echo "[ATP:] the directory ".a:dir." is not removed."
    echohl None
endif
endfunction

    function! ErrorMsg(type)
	let errors		= len(filter(getqflist(),"v:val['type']==a:type"))
	if errors > 1
	    let type		= (a:type == 'E' ? 'errors' : 'warnings')
	else
	    let type		= (a:type == 'E' ? 'error' : 'warning')
	endif
	let msg			= ""
	if errors
	    let msg.=" ".errors." ".type
	endif
	return msg
    endfunction

    augroup ATP_QuickFix_2
	au!
	au FileType qf command! -bang -buffer -nargs=? -complete=custom,DebugComp DebugMode	:call <SID>SetDebugMode(<q-bang>,<f-args>)
	au FileType qf let w:atp_qf_errorfile=&l:errorfile
	au FileType qf setl statusline=%{w:atp_qf_errorfile}%=\ %#WarningMsg#%{ErrorMsg('W')}\ %{ErrorMsg('E')}
	au FileType qf exe "resize ".min([atplib#qflength(), g:atp_DebugModeQuickFixHeight])
    augroup END

    function! <SID>BufEnterCgetfile()
	if !exists("b:atp_ErrorFormat")
	    return
	endif
	" Do not execute :cgetfile if we are moving out of a quickfix buffer,
	" or switching between project files unless b:atp_autex == 2.
	if exists("s:leaving_buffer") && 
		    \ ( s:leaving_buffer == 'quickfix'
		    \ ||(exists("b:ListOfFiles") && index(map(b:ListOfFiles, 'atplib#FullPath(v:val)'), s:leaving_buffer) != -1 ||
		    \ exists("b:atp_MainFile") && atplib#FullPath(b:atp_MainFile) == s:leaving_buffer ) &&
		    \ exists("b:atp_autex") && b:atp_autex < 2
		    \ )
	    unlet s:leaving_buffer
	    return
	endif
	if g:atp_cgetfile 
	    try
		" This command executes cgetfile:
		exe "ErrorFormat ".b:atp_ErrorFormat
	    catch /E40:/ 
	    endtry
	endif
    endfunction
    function! <SID>BufLeave()
	if &buftype == 'quickfix'
	    let s:leaving_buffer='quickfix'
	else
	    let s:leaving_buffer=expand("%:p")
	endif
    endfunction
if (v:version < 703 || v:version == 703 && !has("patch648")) && (!exists("g:patched_vim") || exists("g:patched_vim") && !g:patched_vim)
    augroup ATP_QuickFix_cgetfile
"     When using cgetfile the position in quickfix-window is lost, which is
"     annoying when changing windows. 
	au!
	au BufLeave *		:call <SID>BufLeave()
	au BufEnter *.tex 	:call <SID>BufEnterCgetfile()
    augroup END
else
    function! <SID>Latex_Log() 
	if exists("b:atp_MainFile")
	    let log_file  = fnamemodify(atplib#FullPath(b:atp_MainFile), ":r").".log"
	    let _log_file = fnamemodify(atplib#FullPath(b:atp_MainFile), ":r")."._log"
	    if !filereadable(log_file)
		return
	    endif
	    " Run latex_log.py only if log_file is newer than _log_file. 
	    " This is only if the user run latex manualy, since ATP calles
	    " latex_log.py after compilation.
	    if !filereadable(_log_file) || !exists("*getftime") || getftime(log_file) > getftime(_log_file)
		call system("python ".shellescape(split(globpath(&rtp, "ftplugin/ATP_files/latex_log.py"), "\n")[0])." ".shellescape(fnamemodify(atplib#FullPath(b:atp_MainFile), ":r").".log"))
	    endif
	endif
    endfunction
    augroup ATP_QuickFix_cgetfile
	au QuickFixCmdPre cgetfile,cfile,cfileadd 	:call <SID>Latex_Log()
	au QuickFixCmdPost cgetfile,cfile,cfileadd 	:call atplib#compiler#FilterQuickFix()
    augroup END
endif

    augroup ATP_VimLeave
	au!
	" Remove b:atp_TempDir (where compelation is done).
	au VimLeave *.tex :call <SID>Rmdir(b:atp_TempDir)
	" Remove TempDir for debug files.
	au VimLeave *     :call <SID>RmTempDir()
	" :Kill! (i.e. silently if there is no python support.)
	au VimLeave *.tex :Kill!
    augroup END

    function! <SID>UpdateTime(enter)
	if a:enter	== "Enter" && b:atp_updatetime_insert != 0
	    let &l:updatetime	= b:atp_updatetime_insert
	elseif a:enter 	== "Leave" && b:atp_updatetime_normal != 0
	    let &l:updatetime	= b:atp_updatetime_normal
	endif
    endfunction

    augroup ATP_UpdateTime
	au!
	au InsertEnter *.tex :call <SID>UpdateTime("Enter")
	au InsertLeave *.tex :call <SID>UpdateTime("Leave")
    augroup END

    if (exists("g:atp_StatusLine") && g:atp_StatusLine == '1') || !exists("g:atp_StatusLine")
	" Note: ctoc doesn't work in include files (and it is slow there).
	if exists("b:TypeDict")
	    let g:atp_ctoc = !( len(filter(copy(b:TypeDict), 'v:val == "input"')) )
	else
	    let g:atp_ctoc = atplib#FullPath(b:atp_MainFile) != expand("%:p")
	endif
	augroup ATP_Status
	    au!
	    au BufEnter,BufWinEnter,TabEnter *.tex 	call ATPStatus(0,g:atp_ctoc)
	augroup END
    endif

    if g:atp_local_completion == 2
	augroup ATP_LocalCommands
	    au!
	    au BufEnter *.tex 	call LocalCommands(0)
	augroup END
    endif

    augroup ATP_Packages
	au!
	au BufEnter *.tex call <SID>ReadPackageFiles()
    augroup END

    augroup ATP_TeXFlavor
	au!
	au FileType *tex 	let b:atp_TexFlavor = &filetype
    augroup END

    " Idea:
    " au 		*.log if LogBufferFileDiffer | silent execute '%g/^\s*$/d' | w! | endif
    " or maybe it is better to do that after latex made the log file in the call back
    " function, but this adds something to every compilation process !
    " This changes the cursor position in the log file which is NOT GOOD.
"     au WinEnter	*.log	execute "normal m'" | silent execute '%g/^\s*$/d' | execute "normal ''"

    " Experimental:
	" This doesn't work !
" 	    fun! GetSynStackI()
" 		let synstack=[]
" 		let synstackI=synstack(line("."), col("."))
" 		try 
" 		    let test =  synstackI == 0
" 		    let b:return 	= 1
" 		    catch /Can only compare List with List/
" 		    let b:return	= 0
" 		endtry
" 		if b:return == 0
" 		    return []
" 		else
" 		    return map(synstack, "synIDattr(v:val, 'name')")
" 		endif
" 	    endfunction

    " The first one is not working! (which is the more important of these two :(
"     au CursorMovedI *.tex let g:atp_synstackI	= GetSynStackI()
    " This has problems in visual mode:
"     au CursorMoved  *.tex let g:atp_synstack	= map(synstack(line('.'), col('.')), "synIDattr(v:val, 'name')")
    
endif
" }}}

" This function and the following autocommand toggles the textwidth option if
" editing a math mode. Currently, supported are $:$, \(:\), \[:\] and $$:$$.
" {{{  SetMathVimOptions

if !exists("g:atp_SetMathVimOptions")
    let g:atp_SetMathVimOptions 	= 1
endif

if !exists("g:atp_MathVimOptions")
"     { 'option_name' : [ val_in_math, normal_val], ... }
    let g:atp_MathVimOptions 		=  { 'textwidth' 	: [ 0, 	&textwidth],
						\ }
endif

if !exists("g:atp_MathZones")
let g:atp_MathZones	= ( &l:filetype == "tex" ? [ 
	    		\ 'texMathZoneV', 	'texMathZoneW', 
	    		\ 'texMathZoneX', 	'texMathZoneY',
	    		\ 'texMathZoneA', 	'texMathZoneAS',
	    		\ 'texMathZoneB', 	'texMathZoneBS',
	    		\ 'texMathZoneC', 	'texMathZoneCS',
	    		\ 'texMathZoneD', 	'texMathZoneDS',
	    		\ 'texMathZoneE', 	'texMathZoneES',
	    		\ 'texMathZoneF', 	'texMathZoneFS',
	    		\ 'texMathZoneG', 	'texMathZoneGS',
	    		\ 'texMathZoneH', 	'texMathZoneHS',
	    		\ 'texMathZoneI', 	'texMathZoneIS',
	    		\ 'texMathZoneJ', 	'texMathZoneJS',
	    		\ 'texMathZoneK', 	'texMathZoneKS',
	    		\ 'texMathZoneL', 	'texMathZoneLS',
			\ 'texMathZoneT'
			\ ]
			\ : [ 'plaintexMath' ] )
endif

" a:0 	= 0 check if in math mode
" a:1   = 0 assume cursor is not in math
" a:1	= 1 assume cursor stands in math  
function! SetMathVimOptions(...)

	if !g:atp_SetMathVimOptions
	    return "no setting to toggle" 
	endif

	let MathZones = copy(g:atp_MathZones)
	    
	" Change the long values to numbers 
	let MathVimOptions = map(copy(g:atp_MathVimOptions),
			\ " v:val[0] =~ v:key ? [ v:val[0] =~ '^no' . v:key ? 0 : 1, v:val[1] ] : v:val " )
	let MathVimOptions = map(MathVimOptions,
			\ " v:val[1] =~ v:key ? [ v:val[0], v:val[1] =~ '^no' . v:key ? 0 : 1 ] : v:val " )

	" check if the current (and 3 steps back) cursor position is in math
	" or use a:1
" 	let check	= a:0 == 0 ? atplib#complete#CheckSyntaxGroups(MathZones) + atplib#complete#CheckSyntaxGroups(MathZones, line("."), max([ 1, col(".")-3])) : a:1
	let check	= a:0 == 0 ? atplib#IsInMath() : a:1

	if check
	    for option_name in keys(MathVimOptions)
		execute "let &l:".option_name. " = " . MathVimOptions[option_name][0]
	    endfor
	else
	    for option_name in keys(MathVimOptions)
		execute "let &l:".option_name. " = " . MathVimOptions[option_name][1]
	    endfor
	endif

endfunction

if !s:did_options

    augroup ATP_SetMathVimOptions
	au!
	" if leaving the insert mode set the non-math options
	au InsertLeave 	*.tex 	:call SetMathVimOptions(0)
	" if entering the insert mode or in the insert mode check if the cursor is in
	" math or not and set the options acrodingly
	au InsertEnter	*.tex 	:call SetMathVimOptions()
" This is done by atplib#ToggleIMap() function, which is run only when cursor
" enters/leaves LaTeX math mode:
" 	au CursorMovedI *.tex 	:call s:SetMathVimOptions()
    augroup END

endif
"}}}

" SYNTAX GROUPS:
" {{{1 ATP_SyntaxGroups
function! <SID>ATP_SyntaxGroups()
    if &filetype == ""
	" this is important for :Dsearch window
	return
    endif
    " add texMathZoneT syntax group for tikzpicture environment:
    if atplib#search#SearchPackage('tikz') || atplib#search#SearchPackage('pgfplots')
	" This works with \matrix{} but not with \matrix[matrix of math nodes]
	" It is not working with tikzpicture environment inside mathematics.
	syntax cluster texMathZones add=texMathZoneT
	syntax region texMathZoneT start='\\begin\s*{\s*tikzpicture\s*}' end='\\end\s*{\s*tikzpicture\s*}' keepend containedin=@texMathZoneGroup contains=@texMathZoneGroup,@texMathZones,@NoSpell
	syntax sync match texSyncMathZoneT grouphere texMathZoneT '\\begin\s*{\s*tikzpicture\s*}'
	" The function TexNewMathZone() will mark whole tikzpicture
	" environment as a math environment.  This makes problem when one
	" wants to close \(:\) inside tikzpicture.  
" 	call TexNewMathZone("T", "tikzpicture", 0)
    endif
    " add texMathZoneALG syntax group for algorithmic environment:
    if atplib#search#SearchPackage('algorithmic')
	try
	    call TexNewMathZone("ALG", "algorithmic", 0)
	catch /E117:/ 
	endtry
    endif
endfunction

augroup ATP_SyntaxGroups
    au!
    au BufEnter *.tex :call <SID>ATP_SyntaxGroups()
augroup END

augroup ATP_Devel
    au!
    au BufEnter *.sty	:setl nospell	
    au BufEnter *.cls	:setl nospell
    au BufEnter *.fd	:setl nospell
augroup END
"}}}1
"{{{1 Highlightings in help file
augroup ATP_HelpFile_Highlight
    au!
    au BufEnter automatic-tex-plugin.txt call matchadd(hlexists('atp_FileName') ? "atp_FileName" : "Title",  'highlight atp_FileName\s\+Title')
    au BufEnter automatic-tex-plugin.txt call matchadd(hlexists('atp_LineNr') 	? "atp_LineNr"   : "LineNr", 'highlight atp_LineNr\s\+LineNr')
    au BufEnter automatic-tex-plugin.txt call matchadd(hlexists('atp_Number') 	? "atp_Number"   : "Number", 'highlight atp_Number\s\+Number')
    au BufEnter automatic-tex-plugin.txt call matchadd(hlexists('atp_Chapter') 	? "atp_Chapter"  : "Label",  'highlight atp_Chapter\s\+Label')
    au BufEnter automatic-tex-plugin.txt call matchadd(hlexists('atp_Section') 	? "atp_Section"  : "Label",  'highlight atp_Section\s\+Label')
    au BufEnter automatic-tex-plugin.txt call matchadd(hlexists('atp_SubSection') ? "atp_SubSection": "Label", 'highlight atp_SubSection\s\+Label')
    au BufEnter automatic-tex-plugin.txt call matchadd(hlexists('atp_Abstract')	? "atp_Abstract" : "Label", 'highlight atp_Abstract\s\+Label')

    au BufEnter automatic-tex-plugin.txt call matchadd(hlexists('atp_label_FileName') 	? "atp_label_FileName" 	: "Title",	'^\s*highlight atp_label_FileName\s\+Title\s*$')
    au BufEnter automatic-tex-plugin.txt call matchadd(hlexists('atp_label_LineNr') 	? "atp_label_LineNr" 	: "LineNr",	'^\s*highlight atp_label_LineNr\s\+LineNr\s*$')
    au BufEnter automatic-tex-plugin.txt call matchadd(hlexists('atp_label_Name') 	? "atp_label_Name" 	: "Label",	'^\s*highlight atp_label_Name\s\+Label\s*$')
    au BufEnter automatic-tex-plugin.txt call matchadd(hlexists('atp_label_Counter') 	? "atp_label_Counter" 	: "Keyword",	'^\s*highlight atp_label_Counter\s\+Keyword\s*$')

    au BufEnter automatic-tex-plugin.txt call matchadd(hlexists('bibsearchInfo')	? "bibsearchInfo"	: "Number",	'^\s*highlight bibsearchInfo\s*$')
augroup END
"}}}1

" {{{1 :Viewer, :Compiler, :DebugMode
function! <SID>Viewer(...) 
    if a:0 == 0 || a:1 =~ '^\s*$'
	echomsg "[ATP:] current viewer: ".b:atp_Viewer
	return
    else
	let new_viewer = a:1
    endif
    let old_viewer	= b:atp_Viewer
    let oldViewer	= get(g:ViewerMsg_Dict, matchstr(old_viewer, '^\s*\zs\S*'), "")
    let b:atp_Viewer	= new_viewer
    let Viewer		= get(g:ViewerMsg_Dict, matchstr(b:atp_Viewer, '^\s*\zs\S*'), "")
    silent! execute "aunmenu Latex.View\\ with\\ ".oldViewer
    silent! execute "aunmenu Latex.View\\ Output"
    if Viewer != ""
	execute "menu 550.10 LaTe&X.&View\\ with\\ ".Viewer."<Tab>:ViewOutput 		:<C-U>ViewOutput<CR>"
	execute "cmenu 550.10 LaTe&X.&View\\ with\\ ".Viewer."<Tab>:ViewOutput 		<C-U>ViewOutput<CR>"
	execute "imenu 550.10 LaTe&X.&View\\ with\\ ".Viewer."<Tab>:ViewOutput 		<Esc>:ViewOutput<CR>a"
    else
	execute "menu 550.10 LaTe&X.&View\\ Output\\ <Tab>:ViewOutput 		:<C-U>ViewOutput<CR>"
	execute "cmenu 550.10 LaTe&X.&View\\ Output\\ <Tab>:ViewOutput 		<C-U>ViewOutput<CR>"
	execute "imenu 550.10 LaTe&X.&View\\ Output\\ <Tab>:ViewOutput 		<Esc>:ViewOutput<CR>a"
    endif
endfunction
command! -buffer -nargs=? -complete=customlist,ViewerComp Viewer	:call <SID>Viewer(<q-args>)
function! ViewerComp(A,L,P)
    let view = [ 'open', 'okular', 'xpdf', 'xdvi', 'evince', 'epdfview', 'kpdf', 'acroread', 'zathura', 'gv',
		\  'AcroRd32.exe', 'sumatrapdf.exe' ]
    " The names of Windows programs (second line) might be not right [sumatrapdf.exe (?)].
    call filter(view, "v:val =~ '^' . a:A")
    call filter(view, 'executable(v:val)')
    return view
endfunction

function! <SID>Compiler(...) 
    if a:0 == 0
	echo "[ATP:] b:atp_TexCompiler=".b:atp_TexCompiler
	return
    else
	let compiler		= a:1
	let old_compiler	= b:atp_TexCompiler
	let oldCompiler	= get(g:CompilerMsg_Dict, matchstr(old_compiler, '^\s*\zs\S*'), "")
	let b:atp_TexCompiler	= compiler
	let Compiler		= get(g:CompilerMsg_Dict, matchstr(b:atp_TexCompiler, '^\s*\zs\S*'), "")
	silent! execute "aunmenu Latex.".oldCompiler
	silent! execute "aunmenu Latex.".oldCompiler."\\ debug"
	silent! execute "aunmenu Latex.".oldCompiler."\\ twice"
	execute "menu 550.5 LaTe&X.&".Compiler."<Tab>:TEX				:<C-U>TEX<CR>"
	execute "cmenu 550.5 LaTe&X.&".Compiler."<Tab>:TEX				<C-U>TEX<CR>"
	execute "imenu 550.5 LaTe&X.&".Compiler."<Tab>:TEX				<Esc>:TEX<CR>a"
	execute "menu 550.6 LaTe&X.".Compiler."\\ debug<Tab>:TEX\\ debug		:<C-U>DTEX<CR>"
	execute "cmenu 550.6 LaTe&X.".Compiler."\\ debug<Tab>:TEX\\ debug		<C-U>DTEX<CR>"
	execute "imenu 550.6 LaTe&X.".Compiler."\\ debug<Tab>:TEX\\ debug		<Esc>:DTEX<CR>a"
	execute "menu 550.7 LaTe&X.".Compiler."\\ &twice<Tab>:2TEX			:<C-U>2TEX<CR>"
	execute "cmenu 550.7 LaTe&X.".Compiler."\\ &twice<Tab>:2TEX			<C-U>2TEX<CR>"
	execute "imenu 550.7 LaTe&X.".Compiler."\\ &twice<Tab>:2TEX			<Esc>:2TEX<CR>a"
    endif
endfunction
command! -buffer -nargs=? -complete=customlist,CompilerComp Compiler	:call <SID>Compiler(<f-args>)
function! CompilerComp(A,L,P)
    let compilers = [ 'tex', 'pdftex', 'latex', 'pdflatex', 'etex', 'xetex', 'luatex', 'xelatex' ]
"     let g:compilers = copy(compilers)
    call filter(compilers, "v:val =~ '^' . a:A")
    call filter(compilers, 'executable(v:val)')
    return compilers
endfunction

function! <SID>SetDebugMode(bang,...)
    let g:efm_b = &efm
    if a:0 == 0
	echo t:atp_DebugMode
	return
    else
	let match = matchlist(a:1, '^\(auto\)\?\(.*$\)')
	let auto = match[1]
	let mode = match[2]
	if mode =~# '^s\%[silent]'
	    let t:atp_DebugMode= auto.'silent'
	elseif mode =~# '^d\%[debug]'
	    let t:atp_DebugMode= auto.'debug'
	elseif mode =~# '^D\%[debug]'
	    let t:atp_DebugMode= auto.'Debug'
	elseif mode =~# '^v\%[erbose]'
	    let t:atp_DebugMode= auto.'verbose'
	else
	    let t:atp_DebugMode= auto.g:atp_DefaultDebugMode
	endif
    endif

    let g:efm_a = &efm

    if t:atp_DebugMode =~# 'Debug$' && a:1 =~# 'debug$' || t:atp_DebugMode =~# 'debug$' && a:1 =~# 'Debug$'
	let change_menu 	= 0
    else
	let change_menu 	= 1
    endif

    "{{{ Change menu
    if change_menu && t:atp_DebugMode !~? 'debug$'
	silent! aunmenu 550.20.5 Latex.Log.Toggle\ &Debug\ Mode\ [on]
	silent! aunmenu 550.20.5 Latex.Log.Toggle\ &Debug\ Mode\ [off]
	menu 550.20.5 &Latex.&Log.Toggle\ &Debug\ Mode\ [off]<Tab>ToggleDebugMode
		    \ :<C-U>ToggleDebugMode<CR>
	cmenu 550.20.5 &Latex.&Log.Toggle\ &Debug\ Mode\ [off]<Tab>ToggleDebugMode
		    \ <C-U>ToggleDebugMode<CR>
	imenu 550.20.5 &Latex.&Log.Toggle\ &Debug\ Mode\ [off]<Tab>ToggleDebugMode
		    \ <Esc>:ToggleDebugMode<CR>a

	silent! aunmenu Latex.Toggle\ Call\ Back\ [on]
	silent! aunmenu Latex.Toggle\ Call\ Back\ [off]
	menu 550.80 &Latex.Toggle\ &Call\ Back\ [off]<Tab>g:atp_callback	
		    \ :<C-U>ToggleDebugMode<CR>
	cmenu 550.80 &Latex.Toggle\ &Call\ Back\ [off]<Tab>g:atp_callback	
		    \ <C-U>ToggleDebugMode<CR>
	imenu 550.80 &Latex.Toggle\ &Call\ Back\ [off]<Tab>g:atp_callback	
		    \ <Esc>:ToggleDebugMode<CR>a
    elseif change_menu
	silent! aunmenu 550.20.5 Latex.Log.Toggle\ Debug\ Mode\ [off]
	silent! aunmenu 550.20.5 Latex.Log.Toggle\ &Debug\ Mode\ [on]
	menu 550.20.5 &Latex.&Log.Toggle\ &Debug\ Mode\ [on]<Tab>ToggleDebugMode
		    \ :<C-U>ToggleDebugMode<CR>
	cmenu 550.20.5 &Latex.&Log.Toggle\ &Debug\ Mode\ [on]<Tab>ToggleDebugMode
		    \ <C-U>ToggleDebugMode<CR>
	imenu 550.20.5 &Latex.&Log.Toggle\ &Debug\ Mode\ [on]<Tab>ToggleDebugMode
		    \ <Esc>:ToggleDebugMode<CR>a

	silent! aunmenu Latex.Toggle\ Call\ Back\ [on]
	silent! aunmenu Latex.Toggle\ Call\ Back\ [off]
	menu 550.80 &Latex.Toggle\ &Call\ Back\ [on]<Tab>g:atp_callback	
		    \ :<C-U>ToggleDebugMode<CR>
	cmenu 550.80 &Latex.Toggle\ &Call\ Back\ [on]<Tab>g:atp_callback	
		    \ <C-U>ToggleDebugMode<CR>
	imenu 550.80 &Latex.Toggle\ &Call\ Back\ [on]<Tab>g:atp_callback	
		    \ <Esc>:ToggleDebugMode<CR>a
    endif "}}}

    if a:1 =~# '\%(auto\)\?s\%[ilent]'
	let winnr=winnr()
" 	let quickfix_open = 0
" 	windo let quickfix_open += ( &buftype == 'quickfix' ? 1 : 0 )
" 	wincmd w
	if t:atp_QuickFixOpen
	    cclose
	else
	    try
		cgetfile
		call atplib#compiler#FilterQuickFix()
	    catch /E40/
		echohl WarningMsg 
		echo "[ATP:] log file missing."
		echohl None
	    endtry
	    if a:bang == "!"
		exe "cwindow " . (max([1, min([len(getqflist()), g:atp_DebugModeQuickFixHeight])]))
		exe winnr . "wincmd w"
	    endif
	endif
    elseif a:1 =~# '\%(auto\)\?d\%[ebug]'
	let winnr=winnr()
	let g:efm_0 = &efm
	exe "copen " . (!exists("w:quickfix_title") 
		    \ ? (max([1, min([atplib#qflength(), g:atp_DebugModeQuickFixHeight])]))
		    \ : "" )
	let g:efm = &efm
	exe winnr . "wincmd w"
	let g:efm_1 = &efm
	try
	    cgetfile
" 	    call atplib#compiler#FilterQuickFix()
	catch /E40/
	    echohl WarningMsg 
	    echo "[ATP:] log file missing."
	    echohl None
	endtry
	" DebugMode is not changing when log file is missing!
    elseif a:1 =~# '\%(auto\)\?D\%[ebug]'
	let winnr=winnr()
	exe "copen " . (!exists("w:quickfix_title") 
		    \ ? (max([1, min([atplib#qflength(), g:atp_DebugModeQuickFixHeight])]))
		    \ : "" )
	exe winnr . "wincmd w"
	try
	    cgetfile
" 	    call atplib#compiler#FilterQuickFix()
	catch /E40/
	    echohl WarningMsg 
	    echo "[ATP:] log file missing."
	    echohl None
	endtry
	try 
	    cc
	catch E42:
	    echo "[ATP:] no errors."
	endtry
    endif
endfunction
command! -buffer -bang -nargs=? -complete=custom,DebugComp DebugMode	:call <SID>SetDebugMode(<q-bang>,<f-args>)
function! DebugComp(A,L,P)
    return "silent\nautosilent\ndebug\nautodebug\nDebug\nautoDebug\nverbose"
endfunction
"}}}1

" Python test if libraries are present
" (TestPythoLibs() is not runnow, it was too slow)
" {{{
function! <SID>TestPythonLibs()
let time=reltime()
python << END
import vim
try:
    import psutil
except ImportError:
    vim.command('echohl ErrorMsg|echomsg "[ATP:] needs psutil python library."')
    vim.command('echomsg "You can get it from: http://code.google.com/p/psutil/"')
    test=vim.eval("has('mac')||has('macunix')||has('unix')")
    if test != str(0):
	vim.command('echomsg "Falling back to bash"')
	vim.command("let g:atp_Compiler='bash'")
    vim.command("echohl None")
    vim.command("echomsg \"If you don't want to see this message (and you are on *nix system)\"") 
    vim.command("echomsg \"put let g:atp_Compiler='bash' in your vimrc or atprc file.\"")
    vim.command("sleep 2")
END
endfunction

if g:atp_Compiler == "python"
    if !executable(g:atp_Python) || !has("python")
	echohl ErrorMsg
	echomsg "[ATP:] needs: python and python support in vim."
	echohl None
	if has("mac") || has("macunix") || has("unix")
	    echohl ErrorMsg
	    echomsg "I'm falling back to bash (deprecated)."
	    echohl None
	    let g:atp_Compiler = "bash"
	    echomsg "If you don't want to see this message"
	    echomsg "put let g:atp_Compiler='bash' in your vimrc or atprc file."
	    if !has("python")
		echomsg "You Vim is compiled without pyhon support, some tools might not work."
	    endif
	    sleep 2
	endif
"     else
" 	call <SID>TestPythonLibs()
    endif
endif
" }}}

" Remove g:atp_TempDir tree where log files are stored.
function! <SID>RmTempDir() "{{{
if has("python")
python << END
import shutil
temp=vim.eval("g:atp_TempDir")
shutil.rmtree(temp)
END
elseif has("unix") || has("macunix")
    call system("rm -rf ".shellescape(g:atp_TempDir))
else
    echohl ErrorMsg
    echoerr "[ATP:] leaving temporary directory ".g:atp_TempDir
    echohl None
    sleep 1
endif
if isdirectory(g:atp_TempDir)
    echoerr "[ATP]: g:atp_TempDir=".g:atp_TempDir." is not deleted."
endif
endfunction "}}}

" VIM PATH OPTION: 
exe "setlocal path+=".substitute(g:texmf."/tex,".join(filter(split(globpath(b:atp_ProjectDir, '**'), "\n"), "isdirectory(expand(v:val))"), ","), ' ', '\\\\\\\ ', 'g')

" Some Commands:
" {{{
command! -buffer HelpMathIMaps 	:echo atplib#helpfunctions#HelpMathIMaps()
command! -buffer HelpEnvIMaps 	:echo atplib#helpfunctions#HelpEnvIMaps()
command! -buffer HelpVMaps 	:echo atplib#helpfunctions#HelpVMaps()
" }}}

" Help:
silent call atplib#helpfunctions#HelpEnvIMaps()
" vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1
ftplugin/ATP_files/packages/babel.vim	[[[1
38
" This file is a part of ATP.
" Author: Marcin Szamotulski
" Based On: 18/04/2011 (commands up to page 68)

let g:atp_babel_options		= [
	    \ 'afrikaans', 'bahasa', 'indonesian', 'indon', 'bahasai',
	    \ 'bahasam', 'meyalu', 'basque', 'breton',
	    \ 'bulgarian', 'catalan', 'croatian', 'chech',
	    \ 'danish', 'dutch', 'english', 'UKenglish', 'USenglish', 
	    \ 'american', 'british', 'canadian', 'australian', 'newzeland',
	    \ 'esperanto', 'estonian', 'finnish',
	    \ 'french', 'francais', 'canadien', 'acadian', 'galician',
	    \ 'austrian', 'german', 'germanb', 'ngerman', 'naustrian',
	    \ 'greek', 'polutonikogreek', 'hebrew', 'magyar', 'hungarian',
	    \ 'icelandic', 'interlingua', 'irish', 'italian', 'latin',
	    \ 'lowersorbian', 'samin', 'norsk', 'nynorsk', 'polish',
	    \ 'portuges', 'portuguese', 'brazilian', 'brazil', 'romanian', 'russian',
	    \ 'scottish', 'spanish', 'slovak', 'slovene', 'swedish',
	    \ 'serbian', 'turkish', 'ukrainian', 'uppersorbian', 'welsh' ]

let g:atp_babel_environments	= [
	    \ 'otherlanguage', 'otherlanguage*', 'hyphenrules'
	    \ ]
let g:atp_babel_commands	= [
	    \ '\selectlanguage', '\foreignlaguage', '\languagename', '\iflanguage',
	    \ '\useshorthands{', '\defineshorthand', '\aliasshorthand{', '\languageshorthands',
	    \ '\shorthandon', '\shorthandoff', '\languageattribute', '\textormath{',
	    \ '\providehyphenmins', '\langhyphenmins',  '\captionslang',
	    \ '\datelang', '\extraslang', '\noextraslang', '\ProvidesLanguage', '\LdfInit',
	    \ '\loadlocalcfg', '\substitutefontfamily', '\latinencoding', '\latintext', '\textlatin{',
	    \ '\language', '\adddialect', '\iflanguage', '\LdfInit', '\originalTeX', '\readconfigfile',
	    \ '\OT1dqpos', '\T1dqpos', '\addto{', '\quotedblbase', '\quotesingbase', '\guillemotleft',
	    \ '\guillemotright', '\guilsingleleft', '\guilsinglright', 
	    \ '\ij', '\IJ', '\dj', '\DJ', '\SS', '\glq', '\grq',
	    \ '\glqq', '\grqq', '\flq', '\frq', '\flqq', '\frqq', '\umlauthigh', '\umlautlow', '\newlabel{',
	    \ '\ref{', '\pageref{', '\nocite{', '\bibcite', '\vrefpagenum', '\Ref', '\hhline', '\FOREIGNLANGUAGE',
	    \ '\loadlocalcfg'
	    \ ]
ftplugin/ATP_files/packages/beamer.vim	[[[1
86
" This file is a part of ATP.
" Written by Marcin Szamotulski <atp-list@lists.sourceforge.net>
" beamer loads hyperref and its options are available using
" \documentclass[hyperref=<hyperref_option>"]{beamer}
" The same for xcolor package.
"
" Todo: completion for \setbeamerfont command.
let g:atp_beamer_options=["ucs", "utf8", "utf8x", "handout", "hyperref=", "xcolor=", "dvips", 
	    \ "draft", "compress", "t", "c", "aspectratio=", "usepdftitle=", "envcountsect", "notheorems", "noamsthm", 
	    \ "8pt", "9pt", '10pt', '11pt', '12pt', 'smaller', 'bigger', '14pt', '17pt', '20pt', 'trans',
	    \ 'ignorenonframetext', 'notes']
" usepdftitle=[true/false]
let g:atp_beamer_environments = ["frame", "beamercolorbox", "onlyenv", "altenv", 
	    \ "visibleenv", "uncoverenv", "invisibleenv", "overlayarea", "overprint", "actionenv",
	    \ 'description', 'structureenv', 'alertenv', 'block', 'alertblock', 'exampleblock', 'beamercolorbox',
	    \ 'beamerboxesrounded', 'columns', 'semiverbatim' ]

let g:atp_beamer_environment_options = { 
	    \ 'frame' : [ 'allowdisplaybreaks', 'allowframebreaks', 'b', 'c', 't', 'fragile', 'environment=', 'label=', 'sqeeze',  'plain', 'shrink' ]
	    \ }
let g:atp_beamer_commands = ["\\alert{", "\\frametitle{", "\\framesubtitle", "\\titlepage", "\\setbeamercolor{", 
		    \ "\\pause", "\\onslide", "\\only", "\\uncover", "\\visible", "\\invisible", "\\temporal", "\\alt",
		    \ "\\usebeamercolor{", "\\includeonlyframes{", "\\againframe", "\\setbeamersize{",
		    \ "\\action{", "\\inserttocsection", "\\inserttocsectionumber", "\\lecture", "\\AtBeginLecture{",
		    \ "\\appendix", "\\hypertarget", "\\beamerbutton", "\\beamerskipbutton", "\\beamerreturnbutton", 
		    \ "\\beamergotobutton", '\hyperlinkslideprev', '\hyperlinkslidenext', '\hyperlinkframestart', 
		    \ '\hyperlinkframeend', '\hyperlinkframestartnext', '\hyperlinkframeendprev', 
		    \ '\hyperlinkpresentationstart', '\hyperlinkpresentationend', '\hyperlinkappendixstart', 
		    \  '\hyperlinkappendixend', '\hyperlinkdocumentstart',  '\hyperlinkdocumentend',
		    \ '\framezoom', '\structure', '\insertblocktitle', '\column', '\movie', '\animate', 
		    \ '\hyperlinksound', '\hyperlinkmute',
		    \ '\usetheme{', '\usecolortheme{', '\useinnertheme{', '\useoutertheme{',
		    \ '\usefonttheme{', '\note', '\AtBeginNote', '\AtEndNote', '\setbeameroption{',
		    \ '\setbeamerfont{', "\\setbeamertemplate{", '\mode', '\insertframetitle' ]

let g:Local_BeamerThemes=
	\ map(map(
	    \ split(globpath(g:texmf."/tex/latex/beamer/themes/theme", "*.sty"), "\n"), 'fnamemodify(v:val, ":t:r")'),
	\ 'substitute(v:val, ''^beamertheme'', "", "")')
let g:Local_BeamerInnerThemes=
	\ map(map(
	    \ split(globpath(g:texmf."/tex/latex/beamer/themes/inner", "*.sty"), "\n"), 'fnamemodify(v:val, ":t:r")'),
	\ 'substitute(v:val, ''^beamerinnertheme'', "", "")')
let g:Local_BeamerOuterThemes=
	\ map(map(
	    \ split(globpath(g:texmf."/tex/latex/beamer/themes/outer", "*.sty"), "\n"), 'fnamemodify(v:val, ":t:r")'),
	\ 'substitute(v:val, ''^beameroutertheme'', "", "")')
let g:Local_BeamerColorThemes=
	\ map(map(
	    \ split(globpath(g:texmf."/tex/latex/beamer/themes/color", "*.sty"), "\n"), 'fnamemodify(v:val, ":t:r")'),
	\ 'substitute(v:val, ''^beamercolortheme'', "", "")')
let g:Local_BeamerFontThemes=
	\ map(map(
	    \ split(globpath(g:texmf."/tex/latex/beamer/themes/font", "*.sty"), "\n"), 'fnamemodify(v:val, ":t:r")'),
	\ 'substitute(v:val, ''^beamerfonttheme'', "", "")')
let g:BeamerThemes = g:Local_BeamerThemes+[ "default", "boxes", "Bergen", "Boadilla", "Madrid", "AnnArbor", 
	    \ "CambridgeUS", "Pittsburgh", "Rochester", "Antibes", "JuanLesPins", "Montpellier", 
	    \ "Berkeley" , "PalAlto", "Gottingen", "Marburg", "Hannover", "Berlin", "Ilmenau", 
	    \ "Dresden", "Darmstadt", "Frankfurt", "Singapore", "Szeged", "Copenhagen", "Luebeck", "Malmoe", 
	    \ "Warsaw", ]
let g:BeamerInnerThemes = g:Local_BeamerInnerThemes+[ "default", "circles", "rectangles", "rounded", "inmargin" ]
let g:BeamerOuterThemes = g:Local_BeamerOuterThemes+[ "default", "infolines", "miniframes", "smoothbars", "sidebar",
	    \ "split", "shadow", "tree", "smoothtree" ]
let g:BeamerColorThemes = g:Local_BeamerColorThemes+[ "default", "structure", "sidebartab", "albatross", "beetle", "crane", 
	    \ "dove", "fly", "seagull", "wolverine", "beaver", "lily", "orchid", "rose", "whale", "seahorse", 
	    \ "dolphin" ]
let g:BeamerFontThemes = g:Local_BeamerFontThemes+[ "default", "serif", "structurebold", "structureitalicserif",
	    \ "structuresmallcapsserif" ]

let g:BeamerElements = sort([ 'alerted text', 'background canvas', 'block body alerted', 'block body', 'block body example', 'block title alerted', 'block title', 'block title example', 'fine separation line', 'frametitle', 'item projected', 'palette sidebar primary', 'palette sidebar queternary', 'palette sidebar secondary', 'palette sidebar tertiary', 'section in sidebar', 'section in sidebar shaded', 'sidebar', 'structure', 'subsection in sidebar', 'subsection in sidebar shaded', 'title', 'titlelike', 'section in  head/foot', 'title in head/foot'])
let g:BeamerOption   = [ 'show notes', 'hide notes', 'show notes on second screen', 'show only notes', 
	    \ 'second mode text on second screen', 'always typeset second mode', 'previous slide on second screen']
let g:BeamerSizes    = [ 'sidebar width left=', 'sidebar width right=', 'mini frame size=', 'mini frame offset=', 
	    \ 'text margin left=', 'text margin right=', 'description width=', 'description width of=' ]

let g:atp_beamer_command_values = {
	    \ '\\usetheme{$' 		: g:BeamerThemes,
	    \ '\\useinnertheme{$' 	: g:BeamerInnerThemes,
	    \ '\\useoutertheme{$' 	: g:BeamerOuterThemes,
	    \ '\\usecolortheme{$' 	: g:BeamerColorThemes,
	    \ '\\usefonttheme{$' 	: g:BeamerFontThemes,
	    \ '\\\%(setbeamercolor\|setbeamertemplate\|setbeamerfont\)\s*{$' 	: g:BeamerElements,
	    \ '\\setbeamercolor\s*{[^}]*}\s*{\%(.*=\)\?$' : 'GetColors',
	    \ '\\setbeameroption{$'	: g:BeamerOption,
	    \ '\\setbeamersize{$'	: g:BeamerSizes
	    \ }
ftplugin/ATP_files/packages/biblatex.vim	[[[1
36
" This file is based on package file of latex-suite written by
" Andreas Wagner <Andreas dot Wagner at em dot uni-frankfurt dot de>
" adapted to ATP by Marcin Szamotulski <atp-list@lists.sourceforge.net>
let g:atp_biblatex_options=[
    \ 'style=', 'citestyle=', 'bibstyle=', 'natbib=', 'sorting=', 'sortlos=',
    \ 'sortcites=', 'maxnames=', 'minnames=', 'maxitems=', 'minitems=', 'autocite=',
    \ 'autopunct=', 'babel=', 'block=', 'hyperref=', 'backref=', 'indexing=',
    \ 'loadfiles=', 'refsection=', 'refsegment=', 'citereset=', 'abbreviate=', 'date=',
    \ 'urldate=', 'defernums=', 'punctfont=', 'arxiv=', 'backend=', 'mincrossrefs=',
    \ 'bibencoding=', 'useauthor=', 'useeditor=', 'usetranslator=', 'useprefix=', 'skipbib=',
    \ 'skiplos=', 'skiplab=', 'dataonly=', 'pagetracker=', 'citetracker=', 'ibidtracker=',
    \ 'idemtracker=', 'opcittracker=', 'loccittracker=', 'firstinits=', 'terseinits=', 'labelalpha=',
    \ 'labelnumber=', 'labelyear=', 'singletitle=', 'uniquename=', 'openbib' ] 

" This is get using g:atp_package_dict.ScanPackage
let options = ['debug', 'backend', 'loadfiles', 'mincrossrefs', 'texencoding',
	    \ 'bibencoding', 'safeinputenc', 'sorting', 'sortcase', 'sortupper',
	    \ 'sortlocale', 'sortlos', 'maxnames', 'minnames', 'maxnames', 'minnames',
	    \ 'maxnames', 'minnames', 'maxbibnames', 'minbibnames', 'maxbibnames',
	    \ 'minbibnames', 'maxbibnames', 'minbibnames', 'maxcitenames', 'mincitenames',
	    \ 'maxcitenames', 'mincitenames', 'maxcitenames', 'mincitenames', 'maxitems',
	    \ 'minitems', 'maxitems', 'minitems', 'maxitems', 'minitems', 'maxalphanames',
	    \ 'minalphanames', 'maxalphanames', 'minalphanames', 'maxline', 'terseinits',
	    \ 'firstinits', 'abbreviate', 'dateabbrev', 'language', 'clearlang', 'babel',
	    \ 'indexing', 'indexing', 'indexing', 'sortcites', 'hyperref', 'backref',
	    \ 'backrefsetstyle', 'block', 'pagetracker', 'citecounter', 'citetracker',
	    \ 'ibidtracker', 'idemtracker', 'opcittracker', 'loccittracker', 'parentracker',
	    \ 'maxparens', 'date', 'urldate', 'eventdate', 'origdate', 'alldates',
	    \ 'datezeros', 'autocite', 'notetype', 'autopunct', 'punctfont', 'labelnumber',
	    \ 'labelnumber', 'labelalpha', 'labelalpha', 'labelyear', 'labelyear',
	    \ 'uniquelist', 'uniquelist', 'uniquename', 'uniquename', 'singletitle',
	    \ 'singletitle', 'defernumbers', 'refsection', 'refsegment', 'citereset',
	    \ 'bibwarn', 'useprefix', 'useprefix', 'useprefix', 'useauthor', 'useauthor',
	    \ 'useauthor', 'useeditor', 'useeditor', 'useeditor', 'usetranslator',
	    \ 'usetranslator', 'usetranslator', 'skipbib', 'skipbib', 'skiplos', 'skiplos',
	    \ 'skiplab', 'skiplab', 'dataonly', 'dataonly']
ftplugin/ATP_files/packages/bibref.vim	[[[1
10
" This file is a part of ATP.
" Written by M.Szamotulski.
" Based On: bibref package documentation 1995/09/28.
" :MakeLatex is not intergrated with makeindex command (using the arguments of
" \newindex commmand supplied with this package).

let g:atp_bibref_commands	= [
	    \ '\newindex{', '\makeindex', '\printindex', '\index', '\shortindexingon', '\shortindexingoff',
	    \ '\proofmodefalse', '\proofmodetrue', '\indexproofstyle{', '\disableindex', '\renewindex{'
	    \ ]
ftplugin/ATP_files/packages/bibunits.vim	[[[1
8
" This file is a part of ATP.
" Written by Marcin Szamotulski
" based on bibunits.sty v2.4 2004/05/12

let g:atp_bibunits_commands	= [ 
	    \ '\bibliographyunit', '\putbib', '\defaultbibliography{', '\defaultbibliographystyle{' ]
let g:atp_bibuits_options	= [
	    \ 'globalcitecopy', 'labelstoglobalaux', 'sectionbib', 'subsectionbib' ]
ftplugin/ATP_files/packages/cancel.vim	[[[1
15
" This file is a part of ATP.
" Written by Marcin Szamotulski
" based on cancel.sty v2.1
let g:atp_cancel_options 	= [
	    \ 'samesize', 'smaller', 'Smaller'
	    \ ]
let g:atp_cancel_commands	= [
	    \ '\cancel{', '\cancelto{', '\bcancel{', '\xcancel{',
	    \ ]
" let colors= ( exists("b:atp_LocalColors") ? b:atp_LocalColors : [] )
" these should be color commands \blue rather than just a color - I should
" check this.
" let g:atp_cancel_command_values={
" 	    \ '\\CancelColor' : colors
" 	    \ }
ftplugin/ATP_files/packages/caption.vim	[[[1
47
" This file is a part of ATP.
" Written by M.Szamotulski.
" Based On: caption package documentation 2008/04/06.
let g:atp_caption_options	= [
	    \ 'format=', 'indentation=',
	    \ 'lableformat=', 'labelsep=',
	    \ 'textformat=', 'justification=',
	    \ 'singlelinecheck=off', 'font=', 'labelfont=', 'textfont=',
	    \ 'margin=', 'margin*=', 'width=', 'oneside', 'twoside', 
	    \ 'minmargin=', 'maxmargin=', 'parskip=', 'hangindent=',
	    \ 'style=', 'skip=', 'position=', 'list=', 'listformat=',
	    \ 'figurename=', 'tablename=', 'listfigurename=', 
	    \ 'listtablename=', 'figurewithin=', 'tablewithin='
	    \ ]
let g:atp_caption_options_values = {
	    \ 'format=$' : [ 'plain', 'hang' ],
	    \ 'labelformat=$' : [ 'default', 'empty', 'simple', 'brace', 'parens' ],
	    \ 'textformat=$' : [ 'simple', 'period' ],
	    \ 'justification=$' : [ 'justified', 'centering', 'centerlast', 'centerfirst', 
					\ 'raggedright', 'RaggedRight', 'raggedleft' ],
	    \ '\%(label\|text\)\?font=$' : [ 'sriptsize', 'footnotesize', 'small', 'normalsize', 
					\ 'large', 'Large', 'normalfont', 'up', 'it', 'sl',
					\ 'sc', 'md', 'bf', 'rm', 'sf', 'tt', 'singlespacing',
					\ 'onehalfspacing', 'stretch=', 'color=', 'normal' ],
	    \ 'labelsep=$' : [ 'none', 'colon', 'period', 'space', 'quad', 'newline', 'endash' ],
	    \ 'style=$' : [ 'base', 'default' ],
	    \ '\%(figure\|table\)\?position=$' : [  'top', 'above', 'bottom', 'below', 'auto' ],
	    \ 'list=$' : [ 'on', 'off' ],
	    \ 'listformat=$' : [ 'empty', 'simple', 'parens', 'subsimple', 'subparens' ],
	    \ '\%(figure\|table\)within=$' : [ 'chapter', 'section', 'none' ],
	    \ }
" Notes own formats can be added using \DeclareCaptionFormat, the same for
" \DeclareCaptionLabelFormat, \DeclareCaptionLabelSeparator
let g:atp_pacakge_caption_commands	= [
	    \ '\caption*{', '\captionof{', '\captionof*{',
	    \ '\captionlistentry{', 
	    \ '\captionsetup{', '\clearcaptionsetup',
	    \ '\showcaptionsetup{', '\ContinuedFloat', '\ContinuedFloat*', 
	    \ '\DeclareCaptionFormat{', '\DeclareCaptionLabelFormat{', 
	    \ '\DeclareCaptionTextFormat{', '\DeclareCaptionLabelSeparator',
	    \ '\DeclareCaptionJustification{', '\DeclareCaptionFont{', '\DeclareCaptionStyle{',
	    \ '\DeclareCaptionListFormat{', '\DeclareCaptionType{'
	    \ ]
" let g:atp_cpation_commands_values = [
" 	    \ { '\\captionsetup', [ 'singlelinecheck=', 
" 	    \ ]
" \captionsetup{singlelinecheck=off} 
ftplugin/ATP_files/packages/cite.vim	[[[1
21
" This file is a part of ATP.
" Author: Marcin Szamotulski
" Based On: cite 2010/09/10

let g:atp_cite_options 	= [
	    \ 'nobreaks', 'superscript', 'ref', 'nospace', 'space',
	    \ 'nosort', 'sort', 'nomove', 'move', 'noadjust', 'adjust',
	    \ 'nocompress', 'compress', 'biblabel'
	    \ ]
let g:atp_pacakge_cite_commands = [
	    \ '\citen', '\citenum', '\citeform{', '\citepunct{', '\citeleft{',
	    \ '\citeright{', '\citemid{', '\citedash{', '\OverciteFont',
	    \ '\citeonline', '\citepunctpenalty', 
	    \ '\citemidpenalty', '\citeprepenalty', '\CiteMoveChars',
	    \ ]

if atplib#search#SearchPackage('cite')
    syn region texRefZone         matchgroup=texStatement start="\\citen\([tp]\*\=\)\={"   keepend end="}\|%stopzone\>"  contains=texComment,texDelimiter
    syn region texRefZone         matchgroup=texStatement start="\\citenum\([tp]\*\=\)\={"   keepend end="}\|%stopzone\>"  contains=texComment,texDelimiter
    syn region texRefZone         matchgroup=texStatement start="\\citeonline\([tp]\*\=\)\={"   keepend end="}\|%stopzone\>"  contains=texComment,texDelimiter
endif
ftplugin/ATP_files/packages/color.vim	[[[1
178
" This file is a part of ATP.
" Written by Marcin Szamotulski
let g:atp_color_options=[
	    \ 'dvips', 'xdvi', 'dvipdf', 'dvipdfm', 'dvipdfmx',
	    \ 'pdftex', 'dvipsone', 'dviwindo', 'emtex', 'dviwin',
	    \ 'pxtexps', 'pctexwin', 'pctexhp', 'pxtex32', 'truetex',
	    \ 'tcidvi', 'vtex', 'oztex', 'textrues', 'xetex',
	    \ 'monochrome', 'usenames', 'dvipsnames'
	    \ ]
let g:atp_color_commands=[
	    \ '\definecolor{', '\color{', '\textcolor{', '\pagecolor{',
	    \ '\colorbox{', '\fcolorbox{', '\ExecuteOptions{', '\DeclareOption{'
	    \ ]
let color_models = [ 'rgb', 'cmyk', 'gray', 'named' ]
let g:atp_color_command_values={
	    \ '\\ExecuteOptions{$' : g:atp_color_options,
	    \ '\%(\\definecolor{[^}]*}{$\|\\%f\?colorbox\[$\|\%(text\|page\)color\[$\)' : color_models,
	    \ '\%(\\\(text\|page\)?color{$\|\\colorbox{$\|\\fcolorbox\%({[^}]*}\)\?{$\)' :  'GetColors'
	    \ }

" This function will be run by TabCompletion (atplib#complete#TabCompletion() in
" autoloac/atplib.vim) to get the color names.
function! GetColors()
    " Colors which always are defined:
    if exists("b:atp_LocalColors")
	let colors=b:atp_LocalColors
    else
	let colors=[]
    endif
    let colors=extend(colors,[ 'red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'black', 'gray', 'white', 'darkgray', 'lightgray', 'brown', 'lime', 'olive', 'orange', 'pink', 'purple', 'teal', 'violet' ])
    let line=getline(atplib#search#SearchPackage('color'))
    if line =~ '\\usepackage\[[^\]]*\<dvipsnames\*\?\>'
	let add_colors = [
		    \	'Apricot',        'Cyan',        'Mahogany',     'ProcessBlue', 'SpringGreen',
		    \	'Aquamarine',     'Dandelion',   'Maroon',       'Purple',      'Tan',
		    \	'Bittersweet',    'DarkOrchid',  'Melon',        'RawSienna',   'TealBlue',
		    \	'Black',          'Emerald',     'MidnightBlue', 'Red',         'Thistle',
		    \	'Blue',           'ForestGreen', 'Mulberry',     'RedOrange',   'Turquoise',
		    \	'BlueGreen',      'Fuchsia',     'NavyBlue',     'RedViolet',   'Violet',
		    \	'BlueViolet',     'Goldenrod',   'OliveGreen',   'Rhodamine',   'VioletRed',
		    \	'BrickRed',       'Gray',        'Orange',       'RoyalBlue',   'White',
		    \	'Brown',          'Green',       'OrangeRed',    'RoyalPurple', 'WildStrawberry',
		    \	'BurntOrange',    'GreenYellow', 'Orchid',       'RubineRed',   'Yellow',
		    \	'CadetBlue',      'JungleGreen', 'Peach',        'Salmon',      'YellowGreen',
		    \	'CarnationPink',  'Lavender',    'Periwinkle',   'SeaGreen',    'YellowOrange',
		    \	'Cerulean',       'LimeGreen',   'PineGreen',    'Sepia',
		    \	'CornflowerBlue', 'Magenta',     'Plum',         'SkyBlue',
		    \ ]
    elseif line =~ '\\usepackage\[[^\]]*\<svgnames\*\?\>'
	let add_colors = [
		    \	'AliceBlue',      'DarkKhaki',      'Green',                'LightSlateGrey',
		    \	'AntiqueWhite',   'DarkMagenta',    'GreenYellow',          'LightSteelBlue',
		    \	'Aqua',           'DarkOliveGreen', 'Grey',                 'LightYellow',
		    \	'Aquamarine',     'DarkOrange',     'Honeydew',             'Lime',
		    \	'Azure',          'DarkOrchid',     'HotPink',              'LimeGreen',
		    \	'Beige',          'DarkRed',        'IndianRed',            'Linen',
		    \	'Bisque',         'DarkSalmon',     'Indigo',               'Magenta',
		    \	'Black',          'DarkSeaGreen',   'Ivory',                'Maroon',
		    \	'BlanchedAlmond', 'DarkSlateBlue',  'Khaki',                'MediumAquamarine',
		    \	'Blue',           'DarkSlateGray',  'Lavender',             'MediumBlue',
		    \	'BlueViolet',     'DarkSlateGrey',  'LavenderBlush',        'MediumOrchid',
		    \	'Brown',          'DarkTurquoise',  'LawnGreen',            'MediumPurple',
		    \	'BurlyWood',      'DarkViolet',     'LemonChiffon',         'MediumSeaGreen',
		    \	'CadetBlue',      'DeepPink',       'LightBlue',            'MediumSlateBlue',
		    \	'Chartreuse',     'DeepSkyBlue',    'LightCoral',           'MediumSpringGreen',
		    \	'Chocolate',      'DimGray',        'LightCyan',            'MediumTurquoise',
		    \	'Coral',          'DimGrey',        'LightGoldenrod',       'MediumVioletRed',
		    \	'CornflowerBlue', 'DodgerBlue',     'LightGoldenrodYellow', 'MidnightBlue',
		    \	'Cornsilk',       'FireBrick',      'LightGray',            'MintCream',
		    \	'Crimson',        'FloralWhite',    'LightGreen',           'MistyRose',
		    \	'Cyan',           'ForestGreen',    'LightGrey',            'Moccasin',
		    \	'DarkBlue',       'Fuchsia',        'LightPink',            'NavajoWhite',
		    \	'DarkCyan',       'Gainsboro',      'LightSalmon',          'Navy',
		    \	'DarkGoldenrod',  'GhostWhite',     'LightSeaGreen',        'NavyBlue',
		    \	'DarkGray',       'Gold',           'LightSkyBlue',         'OldLace',
		    \	'DarkGreen',      'Goldenrod',      'LightSlateBlue',       'Olive',
		    \	'DarkGrey',       'Gray',           'LightSlateGray',       'OliveDrab',
		    \	'Orange',        'Plum',        'Sienna',      'Thistle',
		    \	'OrangeRed',     'PowderBlue',  'Silver',      'Tomato',
		    \	'Orchid',        'Purple',      'SkyBlue',     'Turquoise',
		    \	'PaleGoldenrod', 'Red',         'SlateBlue',   'Violet',
		    \	'PaleGreen',     'RosyBrown',   'SlateGray',   'VioletRed',
		    \	'PaleTurquoise', 'RoyalBlue',   'SlateGrey',   'Wheat',
		    \	'PaleVioletRed', 'SaddleBrown', 'Snow',        'White',
		    \	'PapayaWhip',    'Salmon',      'SpringGreen', 'WhiteSmoke',
		    \	'PeachPuff',     'SandyBrown',  'SteelBlue',   'Yellow',
		    \	'Peru',          'SeaGreen',    'Tan',         'YellowGreen',
		    \	'Pink',          'Seashell',    'Teal',
		    \ ]
    elseif line =~ '\\usepackage\[[^\]]*\<x11names\*\?\>'
	let add_colors = [
		    \	'AntiqueWhite1', 'Chocolate3',      'DeepPink1',    'IndianRed3',
		    \ 	'AntiqueWhite2', 'Chocolate4',      'DeepPink2',    'IndianRed4',
		    \	'AntiqueWhite3', 'Coral1',          'DeepPink3',    'Ivory1',
		    \	'AntiqueWhite4', 'Coral2',          'DeepPink4',    'Ivory2',
		    \	'Aquamarine1',   'Coral3',          'DeepSkyBlue1', 'Ivory3',
		    \	'Aquamarine2',   'Coral4',          'DeepSkyBlue2', 'Ivory4',
		    \	'Aquamarine3',   'Cornsilk1',       'DeepSkyBlue3', 'Khaki1',
		    \	'Aquamarine4',   'Cornsilk2',       'DeepSkyBlue4', 'Khaki2',
		    \	'Azure1',        'Cornsilk3',       'DodgerBlue1',  'Khaki3',
		    \	'Azure2',        'Cornsilk4',       'DodgerBlue2',  'Khaki4',
		    \	'Azure3',        'Cyan1',           'DodgerBlue3',  'LavenderBlush1',
		    \	'Azure4',        'Cyan2',           'DodgerBlue4',  'LavenderBlush2',
		    \	'Bisque1',       'Cyan3',           'Firebrick1',   'LavenderBlush3',
		    \	'Bisque2',       'Cyan4',           'Firebrick2',   'LavenderBlush4',
		    \	'Bisque3',       'DarkGoldenrod1',  'Firebrick3',   'LemonChiffon1',
		    \	'Bisque4',       'DarkGoldenrod2',  'Firebrick4',   'LemonChiffon2',
		    \	'Blue1',         'DarkGoldenrod3',  'Gold1',        'LemonChiffon3',
		    \	'Blue2',         'DarkGoldenrod4',  'Gold2',        'LemonChiffon4',
		    \	'Blue3',         'DarkOliveGreen1', 'Gold3',        'LightBlue1',
		    \	'Blue4',         'DarkOliveGreen2', 'Gold4',        'LightBlue2',
		    \	'Brown1',        'DarkOliveGreen3', 'Goldenrod1',   'LightBlue3',
		    \	'Brown2',        'DarkOliveGreen4', 'Goldenrod2',   'LightBlue4',
		    \	'Brown3',        'DarkOrange1',     'Goldenrod3',   'LightCyan1',
		    \	'Brown4',        'DarkOrange2',     'Goldenrod4',   'LightCyan2',
		    \	'Burlywood1',    'DarkOrange3',     'Green1',       'LightCyan3',
		    \	'Burlywood2',    'DarkOrange4',     'Green2',       'LightCyan4',
		    \	'Burlywood3',    'DarkOrchid1',     'Green3',       'LightGoldenrod1',
		    \	'Burlywood4',    'DarkOrchid2',     'Green4',       'LightGoldenrod2',
		    \	'CadetBlue1',    'DarkOrchid3',     'Honeydew1',    'LightGoldenrod3',
		    \	'CadetBlue2',    'DarkOrchid4',     'Honeydew2',    'LightGoldenrod4',
		    \	'CadetBlue3',    'DarkSeaGreen1',   'Honeydew3',    'LightPink1',
		    \	'CadetBlue4',    'DarkSeaGreen2',   'Honeydew4',    'LightPink2',
		    \	'Chartreuse1',   'DarkSeaGreen3',   'HotPink1',     'LightPink3',
		    \	'Chartreuse2',   'DarkSeaGreen4',   'HotPink2',     'LightPink4',
		    \	'Chartreuse3',   'DarkSlateGray1',  'HotPink3',     'LightSalmon1',
		    \	'Chartreuse4',   'DarkSlateGray2',  'HotPink4',     'LightSalmon2',
		    \	'Chocolate1',    'DarkSlateGray3',  'IndianRed1',   'LightSalmon3',
		    \	'Chocolate2',    'DarkSlateGray4',  'IndianRed2',   'LightSalmon4',
		    \	'ghtSkyBlue1',   'Orange3',        'RosyBrown1',   'SpringGreen3',
		    \	'LightSkyBlue2',   'Orange4',        'RosyBrown2',   'SpringGreen4',
		    \	'LightSkyBlue3',   'OrangeRed1',     'RosyBrown3',   'SteelBlue1',
		    \	'LightSkyBlue4',   'OrangeRed2',     'RosyBrown4',   'SteelBlue2',
		    \	'LightSteelBlue1', 'OrangeRed3',     'RoyalBlue1',   'SteelBlue3',
		    \	'LightSteelBlue2', 'OrangeRed4',     'RoyalBlue2',   'SteelBlue4',
		    \	'LightSteelBlue3', 'Orchid1',        'RoyalBlue3',   'Tan1',
		    \	'LightSteelBlue4', 'Orchid2',        'RoyalBlue4',   'Tan2',
		    \	'LightYellow1',    'Orchid3',        'Salmon1',      'Tan3',
		    \	'LightYellow2',    'Orchid4',        'Salmon2',      'Tan4',
		    \	'LightYellow3',    'PaleGreen1',     'Salmon3',      'Thistle1',
		    \	'LightYellow4',    'PaleGreen2',     'Salmon4',      'Thistle2',
		    \	'Magenta1',        'PaleGreen3',     'SeaGreen1',    'Thistle3',
		    \	'Magenta2',        'PaleGreen4',     'SeaGreen2',    'Thistle4',
		    \	'Magenta3',        'PaleTurquoise1', 'SeaGreen3',    'Tomato1',
		    \	'Magenta4',        'PaleTurquoise2', 'SeaGreen4',    'Tomato2',
		    \	'Maroon1',         'PaleTurquoise3', 'Seashell1',    'Tomato3',
		    \	'Maroon2',         'PaleTurquoise4', 'Seashell2',    'Tomato4',
		    \	'Maroon3',         'PaleVioletRed1', 'Seashell3',    'Turquoise1',
		    \	'Maroon4',         'PaleVioletRed2', 'Seashell4',    'Turquoise2',
		    \	'MediumOrchid1',   'PaleVioletRed3', 'Sienna1',      'Turquoise3',
		    \	'MediumOrchid2',   'PaleVioletRed4', 'Sienna2',      'Turquoise4',
		    \	'MediumOrchid3',   'PeachPuff1',     'Sienna3',      'VioletRed1',
		    \	'MediumOrchid4',   'PeachPuff2',     'Sienna4',      'VioletRed2',
		    \	'MediumPurple1',   'PeachPuff3',     'SkyBlue1',     'VioletRed3',
		    \	'MediumPurple2',   'PeachPuff4',     'SkyBlue2',     'VioletRed4',
		    \	'MediumPurple3',   'Pink1',          'SkyBlue3',     'Wheat1',
		    \	'MediumPurple4',   'Pink2',          'SkyBlue4',     'Wheat2',
		    \	'MistyRose1',      'Pink3',          'SlateBlue1',   'Wheat3',
		    \	'MistyRose2',      'Pink4',          'SlateBlue2',   'Wheat4',
		    \	'MistyRose3',      'Plum1',          'SlateBlue3',   'Yellow1',
		    \	'MistyRose4',      'Plum2',          'SlateBlue4',   'Yellow2',
		    \	'NavajoWhite1',    'Plum3',          'SlateGray1',   'Yellow3',
		    \	'NavajoWhite2',    'Plum4',          'SlateGray2',   'Yellow4',
		    \	'NavajoWhite3',    'Purple1',        'SlateGray3',   'Gray0',
		    \	'NavajoWhite4',    'Purple2',        'SlateGray4',   'Green0',
		    \	'OliveDrab1',      'Purple3',        'Snow1',        'Grey0',
		    \	'OliveDrab2',      'Purple4',        'Snow2',        'Maroon0',
		    \	'OliveDrab3',      'Red1',           'Snow3',        'Purple0',
		    \ 	'OliveDrab4',      'Red2',           'Snow4',
		    \ 	'Orange1',         'Red3',           'SpringGreen1',
		    \ 	'Orange2',         'Red4',           'SpringGreen2'
		    \ ]
    else
	let add_colors=[]
    endif
    call extend(colors, add_colors)
    return colors
endfunction
ftplugin/ATP_files/packages/common.vim	[[[1
11
" This file is a part of ATP.
" Written by Marcin Szamotulski
let g:atp_common_command_values={
	    \ '\\\%(refstepcounter\|addtocounter\|setcounter\|value\|[aA]lph\|arabic\|fnsymbol\|[rR]oman\)\s*{' : [ 'equation', 'part', 'chapter', 'section', 'subsection', 'subsubsection', 'paragraph', 'subparagraph', 'page', 'figure', 'table', 'footnote', 'mpfootnote', 'enumi', 'enumii', 'enumiii', 'enumiv' ],
	    \ '\\includeonly\s*{\%([^}]*,\)\=' : 'ATP_IncludeOnlyFiles'
	    \ }
function! ATP_IncludeOnlyFiles()
    let list =  filter(copy(b:ListOfFiles), "get(b:TypeDict, v:val, '') == 'input'")
    let present = map(split(matchstr(getline(line(".")), '\\includeonly\s*{\zs[^}]*\ze}'), ","), "fnamemodify(v:val, ':p')")
    return filter(list, "index(present,fnamemodify(v:val, ':p')) == -1") 
endfunction
ftplugin/ATP_files/packages/enumitem.vim	[[[1
24
" This file is a part of ATP.
" Author: Marcin Szamotulski
" Based On: enumitem v2.2

let g:atp_enumitem_options = ['ignoredisplayed', 'loadonly', 'shortlabels', 'inline']

let g:atp_enumitem_commands=[
	    \ '\setlist{', '\setenumerate{', '\setdescription{',
	    \ '\setitemize{', '\SetEnumerateShortLabel{', '\newlist{', 
	    \ '\AddEnumerateCounter{', '\setdisplayed{' 
	    \ ]
let s:env_options = [ 'label=', 'label*=', 'start=', 'ref=', 'align=', 'font=',
	\ 'topsep=', 'partopsep=', 'parsep=', 'itemsep=', 'leftmargin=',
	\ 'rightmargin=', 'listparindent=', 'labelwidth=', 'labelsep=', 'labelindent=', 'itemindent=',
	\ 'resume=', 'resume*=', 'beginpenalty=', 'midpenalty=', 'endpenalty=',
	\ 'before=', 'before*=', 'after=', 'after*=', 'style=', 'noitemsep', 'nolistsep', 'nosep',
	\ 'fullwidth', 'widest=' ]

let g:atp_enumitem_environment_options={
    \ '\<\%(enumerate\|itemize\|description\)\>' : s:env_options
    \ }
let g:atp_enumitem_command_values={
    \ '\\set\%(list\%(\[[^\]]*\]\)\=\|enumerate\|description\|itemize\){' : s:env_options
    \ }
ftplugin/ATP_files/packages/geometry.vim	[[[1
40
" This file was based on geometry.pdf 2010/09/12 v5.6
" Maintained by Marcin Szamotulski <atp-list@lists.sourceforge.net>
let g:atp_geometry_options=[
    \ 'verbose', 'landscape', 'portrait', 'twoside',
    \ 'includemp', 'reversemp', 'reversemarginpar', 'nohead', 'nofoot', 'noheadfoot',
    \ 'dvips', 'pdftex', 'vtex', 'truedimen', 'reset', 
    \ 'a0paper', 'a1paper', 'a2paper', 'a3paper', 'a4paper', 'a5paper', 'a6paper', 
    \ 'b0paper', 'b1paper', 'b2paper', 'b3paper', 'b4paper', 'b5paper', 'b6paper', 
    \ 'c0paper', 'c1paper', 'c2paper', 'c3paper', 'c4paper', 'c5paper', 'c6paper', 
    \ 'b0j', 'b1j', 'b2j', 'b3j', 'b4j', 'b5j', 'b6j',
    \ 'ansiapaper', 'ansibpaper', 'ansibpaper', 'ansicpaper', 'ansidpaper', 'ansiepaper',
    \ 'letterpaper', 'executivepaper', 'legalpaper', 
    \ 'paper=', 'papername=', 'paperwidth=', 'paperheight=', 'width=', 'totalwidth=',
    \ 'height=', 'totalheight=', 'left=', 'lmargin=', 'inner', 'right=', 'rmargin=', 'outer',
    \ 'top=', 'tmargin=', 'bottom=', 'bmargin=', 'hscale=', 'vscale=',
    \ 'textwidth=', 'textheight=', 'marginparwidth=', 'marginpar=', 'marginparsep=', 'headheight=',
    \ 'head=', 'headsep=', 'footskip=', 'hoffset=', 'voffset=', 'twosideshift=',
    \ 'mag=', 'columnsep=', 'footnotesep=', 'papersize={', 'total={',
    \ 'body={', 'text={', 'scale={', 'hmargin={', 'vmargin={', 'margin={',
    \ 'offset={', 'hdivide={', 'vdivide={', 'divide={', 'screen', 'layout=',
    \ 'layoutwidth=', 'layoutheight=', 'layouthoffset=', 'layoutvoffset=', 'layoutoffset={',
    \ 'layoutsize=', 'lines', 'includehead', 'includefoot', 'includeheadfoot', 'includeall', 
    \ 'ignorehead', 'ignorefoot', 'ignoreheadfoot', 'ignoreall', 'heightrounded',
    \ 'hmarginratio', 'vmarginratio', 'marginratio', 'ratio', 'hcentering', 'vcentering', 
    \ 'centering', 'nomarginpar', 'twocolumn', 'onecolumn', 'driver=', 'showcrop', 'showframe',
    \ 'assymetric', 'bindingoffset', 'pass'
    \ ]
let g:atp_geometry_options_values = {
    \ '\%(layout\|paper\|papername\)=$' : [ 
	\ 'a0paper', 'a1paper', 'a2paper', 'a3paper', 'a4paper', 'a5paper', 'a6paper',
	\ 'b0paper', 'b1paper', 'b2paper', 'b3paper', 'b4paper', 'b5paper', 'b6paper', 
	\ 'c0paper', 'c1paper', 'c2paper', 'c3paper', 'c4paper', 'c5paper', 'c6paper', 
	\ 'b0j', 'b1j', 'b2j', 'b3j', 'b4j', 'b5j', 'b6j',
	\ 'ansiapaper', 'ansibpaper', 'ansibpaper', 'ansicpaper', 'ansidpaper', 'ansiepaper',
	\ 'letterpaper', 'executivepaper', 'legalpaper'],
    \ 'driver=$' : [ 'dvips', 'dvipdfm', 'pdftex', 'vtex', 'xetex', 'auto', 'none' ] 
    \ } 
let g:atp_geometry_commands=[
    \ '\geometry{', '\newgeometry{', '\savegeometry{', '\restoregeometry', '\loadgeometry{',
    \ ]
ftplugin/ATP_files/packages/graphicx.vim	[[[1
12
" This file is a part of ATP.
" Written by Marcin Szamotulski <atp-list@lists.sourceforge.net>

let g:atp_graphicx_options=['xdvi', 'dvipdf',
	\ 'dvipdfm', 'pdftex', 'dvipsone', 'dviwindo', 'emtex', 'dviwin', 'oztex',
	\ 'textures', 'pctexps', 'pctexwin', 'pctexhp', 'pctex32', 'truetex', 'tcidvi',
	\ 'vtex', 'debugshow', 'draft', 'final', 'hiderotate', 'hiresbb',
	\ 'hidescale', 'unknownkeysallowed', 'unknownkeyserror']
let g:atp_graphicx_commands=[
	\ '\rotatebox{', '\scalebox{', '\resizebox{', '\includegraphics{', '\DeclareGraphicsExtensions{',
	\ '\DeclareGraphicsRule{'
	\ ]
ftplugin/ATP_files/packages/hyperref.vim	[[[1
30
" This file is a part of ATP.
" Written by Marcin Szamotulski <atp-list@lists.sourceforge.net>
let g:atp_hyperref_commands=[ '\hypersetup{', '\hypertarget{', '\url{', '\nolinkurl{', '\hyperbaseurl{', 
	\ '\hyperdef{', '\hyperref', '\hyperlink{', '\phantomsection', '\autoref{', '\autopageref{', 
	\ '\ref*{', '\autoref*{', '\autopageref*{', '\pdfstringdef{', '\pdfbookmark', 
	\ '\curretnpdfbookmark{', '\subpdfbookmark{', '\subpdfbookmark{', '\belowpdfbookmark{',
	\ '\texorpdfstring{', '\hypercalcbp', '\Acrobatmenu{', 
	\ '\textField', '\CheckBox', '\ChoiceMenu', '\PushButton', '\Submit', '\Reset',
	\ '\LayoutTextField', '\LayoutChoiceField', '\LayoutCheckField', '\MakeRadioField{', 
	\ '\MakeCheckField{', '\MakeTextField{', '\MakeChoiceField{', '\MakeButtonField{' ]
let g:atp_hyperref_options=['4=', 'a4paper', 'a5paper', 'anchorcolor=', 'b5paper', 'backref=', 'baseurl={',
	\ 'bookmarks=', 'bookmarksnumbered=', 'bookmarksopen=', 'bookmarksopenlevel=', 'bookmarkstype=',
	\ 'breaklinks=', 'citebordercolor=', 'citecolor=', 'colorlinks=', 'debug=', 'draft', 'dvipdf', 
	\ 'dvipdfm', 'dvips', 'dvipsone', 'dviwindo', 'executivepaper', 'extension=', 'filebordercolor=',
	\ 'filecolor=', 'frenchlinks=', 'hyperfigures=', 'hyperindex=', 'hypertex', 'hypertexnames=', 'implicit=',
	\ 'latex2html', 'legalpaper', 'letterpaper', 'linkbordercolor=', 'linkcolor=', 'linktocpage=',
	\ 'menubordercolor=', 'menucolor=', 'naturalnames', 'nesting=', 'pageanchor=', 'pagebackref=',
	\ 'pagebordercolor=', 'pagecolor=', 'pdfauthor={', 'pdfborder=', 'pdfcenterwindow=', 'pdfcreator={',
	\ 'pdffitwindow', 'pdfhighlight=', 'pdfkeywords={', 'pdfmenubar=', 'pdfnewwindow=', 'pdfpagelabels=',
	\ 'pdfpagelayout=', 'pdfpagemode=', 'pdfpagescrop=', 'pdfpagetransition=', 'pdfproducer={', 'pdfstartpage={',
	\ 'pdfstartview={', 'pdfsubject={', 'pdftex', 'pdftitle={', 'pdftoolbar=', 'pdfusetitle=', 'pdfview',
	\ 'pdfwindowui=', 'plainpages=', 'ps2pdf', 'raiselinks=', 'runbordercolor', 'tex4ht', 'textures',
	\ 'unicode=', 'urlbordercolor=', 'urlcolor=', 'verbose=', 'vtex', 'allcolors=', 'allbordercolors=', 'nativepdf=',
	\ 'pdfdisplaydoctitle=', 'pdfmark=', 'setpagesize=']
let g:atp_hyperref_options_values={
	\ '^\%(anchor\|cite\%(border\)\=\|file\|link\%(border\)\=\|page\%(border\)\=\|url\|menu\)color' : 'GetColors',
	\ '^all\%(border\)\=colors=' : 'GetColors',
	\ '^\%(colorlinks\|frenchlinks\|hidelinks\|hyperfigures\|pagebackref\|hyperindex\|plainpages\|linktocpage\|breaklinks\|bookmarks\%\(open\|numbered\)\=\|naturalnames\|nativepdf\|nesting\|CJKbookmarks\|pdfcenterwindow\|pdfmark\|pdfdisplaydoctitle\|pdffitwindow\|pdfnewwindow\|unicode\|verbose\)=' : [ 'true', 'false' ],
	\ '^\%(bookmarks\|pageanchor\|hyperfootnotes\|pdfmenubar\|pdfpagelabels\|pdftoolbar\|pdfwindowui\|setpagesize\)=' : [ 'false', 'true' ]
	\ }
ftplugin/ATP_files/packages/inputenc.vim	[[[1
12
" This file is a part of ATP.
" Author: Marcin Szamotulski

let g:atp_inputenc_options=[
    \ 'ascii', 'latin1', 'latin2', 'latin3', 'latin4', 'latin5',
    \ 'latin9', 'decmulti', 'cp850', 'cp852', 'cp858', 
    \ 'cp437', 'cp437de', 'cp865', 'applemac', 'macce', 'next',
    \ 'ansinew', 'cp1250', 'cp1252', 'utf8' ]
let g:atp_inputenc_commands=[
    \ '\inputencoding{', '\DeclareInputText{', '\DeclareInputMath{',
    \ '\DeclareUnicodeCharacter{'
    \ ]
ftplugin/ATP_files/packages/libgreek.vim	[[[1
10
" This file is a part of ATP 
" Author: Marcin Szamotulski

let g:atp_libgreek_options		= [
	    \ 'scale=', 'style=', 'style=', 'style=',
	    \ 'greek=', 'Greek=', 'series=', 'boldseries=' ]
let g:atp_libgreek_options_values	= {
	    \ 'style=$' : [ 'ISO', 'French', 'TeX' ]
	    \ }

ftplugin/ATP_files/packages/longtable.vim	[[[1
11
" This file is a part of ATP 
" by Marcin Szamotulski
" based on longtable.sty version 2004/02/01
let g:atp_longtable_options	= [
	\ 'errorshow', 'pausing', 'set', 'final' ]
let g:atp_longtable_commands	= [
	\ '\endhead', '\endfirsthead', '\endfoot', '\endlastfoot',
	\ '\caption', '\multicolumn', '\kill', '\killed',
	\ '\halign', '\setlongtables', '\LTleft{', '\LTright{',
	\ '\LTpre{', '\LTpost{', '\LTcapwidth{', '\tabularnewline',
	\ '\LTchunksize', '\footnotemark', '\footnotetext']
ftplugin/ATP_files/packages/makeidx.vim	[[[1
3
" This file is a part of ATP.
" Written by Marcin Szamotulski
let g:atp_makeidx_commands = [ '\index{', '\see{', '\seealso{', '\seename{', '\alsoname{', '\printindex' ]
ftplugin/ATP_files/packages/mathdesign.vim	[[[1
9
" This file is a part of ATP 
" by Marcin Szamotulski
let g:atp_mathdesign_options	= [
	    \ 'adobe-utopia', 'utopia', 'urw-garamond', 'garamond',
	    \ 'bitstream-charter', 'charter', 'expert', 'euro',
	    \ 'sfscaled=false', 'sfscaled=true', 'ttscaled=false', 'ttscaled=true',
	    \ 'uppercase=false', 'uppercase=true', 
	    \ 'greekuppercase=upright', 'greekuppercase=italicized',
	    \ 'greeklowercase=italicized', 'greeklowercase=upright' ]
ftplugin/ATP_files/packages/mathtools.vim	[[[1
14
let g:atp_mathtools_math_commands = [ '\cramped', '\crampedllap', '\crampedclap', '\crampedrlap', '\smashoperator',
	\ '\adjustlimits', '\newtagform{', '\usetagform{', '\renewtagform{', 
	\ '\xleftrightarrow', '\xRightarrow', '\xLeftarrow', '\xLeftrightarrow', 
	\ '\xhookleftarrow', '\xhookrightarrow', '\xmapsto', '\underbracket{', '\overbracket{',
	\ '\LaTeXunderbrace', '\LaTeXoverbrace', '\Aboxed', '\ArrowBetweenLines', '\ArrowBetweenLines*',
	\ '\shortintertext', '\lparen', '\rparen', '\vcentcolon', 
	\ '\ordinarycolon', '\mathtoolsset{', '\prescript',
	\ '\newgathered', '\renewgathered', '\splitfrac{', '\splitdfrac{' ]
let g:atp_mathtools_commands = [ '\DeclarePairedDelimiter{', '\DeclarePairedDelimiterX{' ]

let g:atp_mathtools_environments = [ 'matrix*', 'pmatrix*', 'bmatrix*', 'Bmatrix*', 'vmatrix*', 'Vmatrix*', 
	\ 'multilined', 'dcases', 'dcases*', 'rcases', 'rcases*', 'drcases*', 'cases*', 'spreadlines',
	\ 'lgathered', 'rgathered' ]

ftplugin/ATP_files/packages/memoir.vim	[[[1
38
" This file is a part of ATP.
" Written by Marcin Szamotulski <atp-list@lists.sourceforge.net>

let g:atp_memoir_options = [
	    \ '9pt', '10pt', '11pt', '12pt', '14pt', '17pt', '20pt', '25pt',
	    \ '30pt', '36pt', '48pt', '60pt', 'extrafontsizes',
	    \ 'a6paper', 'a5paper', 'a4paper', 'a3paper', 
	    \ 'b6paper', 'b5paper', 'b4paper', 'b3paper',
	    \ 'mcrownvopaper', 'mlargecrownvopaper', 'mdemyvopaper', 'msmallroyalvopaper',
	    \ 'latterpaper', 'landscape', 'dbillpaper', 'statementpaper', 'executivepaper',
	    \ 'oldpaper', 'legalpaper', 'ledgerpaper', 'broadsheatpaper',
	    \ 'pottvopaper', 'crownvopaper', 'postvopaper', 'largecrownvopaper', 'largepostvopaper',
	    \ 'smalldemyvopaper', 'demyvopaper', 'mediumvopaper', 'smallroyalpaper', 'royalpaper',
	    \ 'superroyalpaper', 'imperialvopaper',
	    \ 'twoside', 'oneside', 'onecolumn', 'openright', 'openleft', 'openany', 'final', 'draft',
	    \ 'ms', 'showtrims', 'leqno', 'fleqn', 'openbib', 'article', 'oldfontcommands' 
	    \ ]

let g:atp_memoir_commands = [
	    \ '\stockheight', '\trimtop', '\trimedge', '\stockwidth',
	    \ '\spinemargin', '\foremargin', '\uppermargin', '\headmargin',
	    \ '\typeoutlayout', '\typeoutstandardlayout', '\settypeoutlayoutunit{',
	    \ '\fixpdflayout', '\fixdvipslayout', '\medievalpage', '\isopage',
	    \ '\semiisopage',
	    \ '\contentsname', '\listfigurename', 'listtablename'
	    \ ]
let g:atp_memoir_command_values = {
	    \ '\\\%(this\)\=pagestyle\s*{' : [ 'cleared', 'chapter', 'titlingpagestyle' ]
	    \ }
" Additional commands which seems to be rare and thus not included by default.
" Uncomment this line to get them.
" call extend(g:atp_memoir_commands, [
" 	    \ '\setstocksize{', '\settrimmedsize{', '\settypeblocksize{', '\setlrmarigins{', 
" 	    \ '\setlrmarginsandblock{', '\setbinding{', '\setulmargins{', '\setulmarginsandblock{', 
" 	    \ '\setcolsepandrule{', '\setheadfoot{', '\setheaderspaces{',
" 	    \ '\setmarginnotes{', '\checkandfixthelayout', '\checkthelayout',
" 	    \ '\fixthelayout', '\setxlvchars', '\setlxvchars'
" 	    \ ] )
ftplugin/ATP_files/packages/natbib.vim	[[[1
27
" This file is a part of ATP.
" Author: Marcin Szamotulski
" Based On: cite 2010/09/10

" Todo: move \cite completion here and add it dor \shorcites{} command.
let g:atp_natbib_options = [
	    \ 'round', 'square', 'curly', 'angle', 'semicolon', 'colon', 'comma', 'comma', 'authoryear',
	    \ 'numbers', 'super', 'sort', 'sort&compress', 'compress', 'longnamesfirst', 'sectionbib', 
	    \ 'nonamebreak', 'merge', 'elide', 'mcite'
	    \ ]

" This is not working:
let g:atp_natbib_commands = [
	    \ '\citet', '\citep', '\citet*', '\citep*', '\citealt', '\citealp', '\citetext', '\citenum',
	    \ '\citeauthor', '\citeauthor*', '\citeyear', '\Citealt', '\Citealp', '\Citeauthor', 
	    \ '\defcitealias', '\citetalias', '\citepalias', '\setcitestyle{', '\bibpunct{',
	    \ '\citestyle{', '\bibsection', '\bibpreambule', '\bibfont', '\citenumfont', '\bibnumfmt',
	    \ '\bibhang', '\bibsep', '\citeindextrue', '\citeindexfalse', '\shortcites{', '\citestyle{'
	    \ ]
let g:atp_natbib_command_values = {
	    \ '\\setcitestyle\s*{\%(\%([^}]\|{[^}]*}\)*,\)\=$' : ['authoryear', 'numbers', 'super',
						\ 'square', 'open={', 'colse={', 'semicolon',
						\ 'comma', 'citesep={', 'aysep={', 'yysep={',
						\ 'notesep={'
						\ ],
	    \ '\\citestyle{$' : [ 'plain', 'plainnat', 'agu', 'egu', 'agms', 'dcu', 'kulwer', 'cospar', 'nature']
	    \ }
ftplugin/ATP_files/packages/ntheorem.vim	[[[1
23
" This file is a part of ATP.
" Written by Marcin Szamotulski
let g:atp_ntheorem_options	= [
	    \ 'thmmarks', 'amsmath', 'thref' 
	    \ ]
let g:atp_ntheorem_commands	= [ 
	    \ '\newtheorem{', '\renewtheorem{',
	    \ '\theorempreskipamount{', '\theorempostskipamount{',
	    \ '\theoremstyle{', '\theoremheadfont{', '\theorembodyfont{',
	    \ '\theoremseparator{', '\theoremprework{', '\theorempostwork{',
	    \ '\theoremindent{', '\theoremnumbering{', '\theoremsymbol{',
	    \ '\theoremclass{', '\newframedtheorem{', '\newshadedtheorem{',
	    \ '\shadecolor{', '\listtheorems{', '\theoremlisttype{',
	    \ '\addtheoremline{', '\addtotheoremline{', '\newtheoremstyle{',
	    \ '\qed', '\qedsymbol', '\NoEndMark', '\TheoremSymbol', '\thref'
	    \ ]
let s:colors = ( exists("b:atp_LocalColors") ? b:atp_LocalColors : [] )
let g:atp_ntheorem_command_values = {
	    \ '\\theoremstyle{' : [ 'plain', 'break', 'change', 'changebreak', 'margin',
				\ 'marginbreak', 'nonumberplain', 'nonumberbreak', 'empty' ],
	    \ '\\shadecolor{' : s:colors, 
	    \ '\\theoremlisttype{' : [ 'all', 'allname', 'opt', 'optname' ]
	    \ }
ftplugin/ATP_files/packages/showidx.vim	[[[1
4
" This file is a part of ATP.
" Written by Marcin Szamotulski
let g:atp_showidx_commands = [ '\indexbox', '\index{', '\makeindex' ]

ftplugin/ATP_files/packages/standard_classes.vim	[[[1
12
" This file is a part of ATP.
" Written by Marcin Szamotulski <atp-list@lists.sourceforge.net>
let s:options=[
	    \ '10pt', '11pt', '12pt', 'a4paper', 'a5paper', 'letterpaper', 'legalpaper', 
	    \ 'executivepaper', 'landscape', 'titlepage', 'notitlepage', 'leqno', 'reqno', 'fleqn',
	    \ 'openbib', 'draft', 'final', 'oneside', 'twoside', 'openright', 'openany',
	    \ 'onecolumn', 'twocolumn']
let g:atp_article_options	= s:options
let g:atp_report_options	= s:options
let g:atp_letter_options	= s:options
let g:atp_book_options	= s:options
let g:atp_book_options	= s:options
ftplugin/ATP_files/packages/stmaryrd.vim	[[[1
53
" This file is a part of ATP.
" Author: Marcin Szamotulski

let g:atp_stmaryrd_options = [
	    \ 'only', 'mapsfrom', 'Mapsto', 'Mapsfrom',
	    \ 'longarrownot', 'Longarrownot', 'arrownot', 'Arrownot',
	    \ 'longmapsto', 'Longmapsto', 'longmapsfrom', 'Longmapsfrom'
	    \ ]
let g:atp_stmaryrd_math_commands = [
	    \ '\Ydown',        '\Yleft',        '\Yright',
	    \ '\Yup',          '\baro',         '\bbslash',
	    \ '\binampersand', '\bindnasrepma', '\boxast',
	    \ '\boxbar',       '\boxbox',       '\boxbslash',
	    \ '\boxcircle',    '\boxdot',       '\boxempty',
	    \ '\boxslash',            '\curlyveedownarrow', '\curlyveeuparrow',
	    \ '\curlywedgedownarrow', '\curlywedgeuparrow', '\fatbslash',
	    \ '\fatsemi',             '\fatslash',          '\interleave',
	    \ '\leftslice',           '\merge',             '\minuso',
	    \ '\moo',                 '\nplus',             '\obar',
	    \ '\oblong',              '\obslash',           '\ogreaterthan',
	    \ '\olessthan',           '\ovee',              '\owedge',
	    \ '\rightslice',          '\sslash',            '\talloblong',
	    \ '\varbigcirc',          '\varcurlyvee',       '\varcurlywedge',
	    \ '\varoast',             '\varobar',           '\varobslash',
	    \ '\varocircle',          '\varodot',           '\varogreaterthan',
	    \ '\varolessthan',        '\varominus',         '\varoplus',
	    \ '\varoslash',           '\varotimes',         '\varovee',
	    \ '\varowedge',           '\vartimes',
	    \ '\bigbox',        	    	'\bigcurlyvee',     '\bigcurlywedge',
	    \ '\biginterleave', 		'\bignplus',        '\bigparallel',
	    \ '\bigsqcap',      		'\bigtriangledown', '\bigtriangleup',
	    \ '\inplus',                '\niplus',       '\ntrianglelefteqslant',
	    \ '\ntrianglerighteqslant', '\subsetplus',   '\subsetpluseq',
	    \ '\supsetplus',            '\supsetpluseq', '\trianglelefteqslant',
	    \ '\trianglerighteqslant',
	    \ '\Longmapsfrom',            '\Longmapsto',         '\Mapsfrom',
	    \ '\Mapsto',                  '\leftarrowtriangle',  '\leftrightarroweq',
	    \ '\leftrightarrowtriangle',  '\lightning',          '\longmapsfrom',
	    \ '\mapsfrom',                '\nnearrow',           '\nnwarrow',
	    \ '\rightarrowtriangle',      '\rrparenthesis',      '\shortdownarrow',
	    \ '\shortleftarrow',          '\shortrightarrow',    '\shortuparrow',
	    \ '\ssearrow',                '\sswarrow',
	    \ '\Lbag',          '\Rbag',    '\lbag',
	    \ '\llbracket',     '\llceil',  '\llfloor',
	    \ '\llparenthesis', '\rbag',    '\rrbracket',
	    \ '\rrceil',        '\rrfloor',
	    \ '\Arrownot', '\Mapsfromchar', '\Mapstochar',
	    \ '\arrownot', '\mapsfromchar',
	    \ ]
if atplib#search#SearchPackage('amssymb')
    call extend(g:atp_stmaryrd_math_commands, [ '\oast', '\ocircle' ])
endif

ftplugin/ATP_files/packages/syntonly.vim	[[[1
3
" This file is a part of ATP.
" Written by Marcin Szamotulski
let g:atp_syntonly_commands = [ '\syntaxonly' ] 
ftplugin/ATP_files/packages/textcmds.vim	[[[1
16
" This file is a part of ATP.
" Author: Marcin Szamotulski

let g:atp_textcmds_commands=[
	    \ '\mdash', '\ndash', '\qd', '\xd', '\ldq', '\rdq', 
	    \ '\lq', '\rq', '\bul', '\vsp', '\pdc', '\vrt', '\cir', 
	    \ '\til', '\bsl', '\cwm',
	    \ '\q{', '\qq{', '\lara{', '\tsup{', '\tsub{',
	    \ '\textemdash', '\textendash', '\textquestiondown',
	    \ '\textexclamdown', '\textquotedblleft', '\textquotedblright', 
	    \ '\textquoteleft', '\textqouteright', '\textbullet', 
	    \ '\textvisiblespace', '\textperiodcentered', '\textbar', 
	    \ '\textasciicircum', '\textasciitilde', '\textbackslash', 
	    \ '\textcompworkdmark' ]


ftplugin/ATP_files/packages/url.vim	[[[1
12
" This file is a part of ATP.
" Author: Marcin Szamotulski
" Based On: url.sty ver 3.3

let g:atp_url_options	= [
	    \ 'obeyspaces', 'hyphens', 'spaces', 'lowtilde'
	    \ ]
let g:atp_url_commands	= [
	    \ '\url{', '\urlstyle{', '\urldef{',
	    \ '\DeclareUrlCommand{', '\UrlFont', '\UrlBreaks', '\UrlSpacials',
	    \ '\UrlBigBreaks', '\UrlBreaks', '\UrlNoBreaks'
	    \ ]
ftplugin/ATP_files/packages/xcolor.vim	[[[1
204
" This file is a part of ATP.
" Written by Marcin Szamotulski.

"This variable is a dictionary { 'package' : 'option' } which loads xcolor
"package, when option is empty means that the package is always loading.
"Both 'package' and 'option' are vim patterns.
let g:atp_xcolor_loading={ '\%(tikz\|pgf\|color\)' : '' } 

let g:atp_xcolor_options=[
	    \ 'dvips', 'xdvi', 'dvipdf', 'dvipdfm', 'dvipdfmx',
	    \ 'pdftex', 'dvipsone', 'dviwindo', 'emtex', 'dviwin',
	    \ 'pxtexps', 'pctexwin', 'pctexhp', 'pxtex32', 'truetex',
	    \ 'tcidvi', 'vtex', 'oztex', 'textrues', 'xetex',
	    \ 'monochrome', 
	    \ 'natural', 'rgb', 'cmy', 'cmyk', 'hsb', 'gray',
	    \ 'RGB', 'HTML', 'HSB', 'Gray',
	    \ 'dvipsnames', 'dvipsnames*', 'svgnames', 'svgnames*',
	    \ 'x11names', 'x11names*',
	    \ 'table', 'fixpdftex', 'hyperref',
	    \ 'prologue', 'kernelfbox', 'xcdraw', 'noxcdraw', 'fixinclude',
	    \ 'showerrors', 'hideerrors'
	    \ ]
" These are obsolete options:
" 	    \ 'pst', 'override', 'usenames', 'nodvipsnames'
let g:atp_xcolor_commands=[
	    \ '\GetGinDriver', '\GinDriver', '\xcolorcmd',
	    \ '\rangeHsb',  '\rangeRGB', '\rangeHSB', '\rangeGray',
	    \ '\selectcolormodel{', '\ifconvertcolorsD', '\ifconvertcolorsU',
	    \ '\definecolor', '\providecolor{', '\colorlet{', '\definecolorset{',
	    \ '\providecolorset{', '\definecolorserites{', '\definecolors{',
	    \ '\providecolors{', '\DefineNamedColor{', '\preparecolor{',
	    \ '\preparecolorset{', '\ifdeinfecolors', '\xglobal', '\color{',
	    \ '\textcolor{', '\pagecolor{', '\colorbox{', '\fcolorbox{', 
	    \ '\boxframe', '\testcolor{', '\blendcolors', '\colormask', '\maskcolors{',
	    \ '\maskcolorstrue', '\ifmaskcolors', '\resetcolorseries{',
	    \ '\colorseriescycle{', '\rowcolors{', '\showrowcolors',
	    \ '\hiderowcolors', '\rownum', '\extractcolorspecs', '\tracingcolors',
	    \ 'convertcolorspecs{'
	    \ ]
let color_models = [ 'natural', 'rgb', 'cmy', 'cmyk', 'hsb', 'gray',
	    \ 'RGB', 'HTML', 'HSB', 'Gray', 'Hsb', 'tHsb', 'wave' ]
let g:atp_xcolor_command_values={
	    \ '\%(\\\%(text\|page\)\?color{\|\\colorbox{\|\\fcolorbox{\|\\fcolorbox{[^}]*}{\|\\testcolor{\|\\maskcolors\%(\[[^\]]*\]\|\\rowcolors\(\[[^\]]*\]\)\?{[^}]*}{\%([^}]*}{\)\?\)\?{\|color=\)$' : 'GetColors',
	    \ '\%(\\selectcolormodel\s*{\|\\maskcolors\[\|\\convertcolorspec{\)$' : color_models
	    \ }

" This function will be run by TabCompletion (atplib#complete#TabCompletion() in
" autoloac/atplib.vim) to get the color names.
function! GetColors()
    " Colors which always are defined:
    if exists("b:atp_LocalColors")
	let colors=b:atp_LocalColors
    else
	let colors=[]
    endif
    let colors=extend(colors,[ 'red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'black', 'gray', 'white', 'darkgray', 'lightgray', 'brown', 'lime', 'olive', 'orange', 'pink', 'purple', 'teal', 'violet' ])
    let line=getline(atplib#search#SearchPackage('xcolor'))
    if line =~ '\\usepackage\[[^\]]*\<dvipsnames\*\?\>'
	let add_colors = [
		    \	'Apricot',        'Cyan',        'Mahogany',     'ProcessBlue', 'SpringGreen',
		    \	'Aquamarine',     'Dandelion',   'Maroon',       'Purple',      'Tan',
		    \	'Bittersweet',    'DarkOrchid',  'Melon',        'RawSienna',   'TealBlue',
		    \	'Black',          'Emerald',     'MidnightBlue', 'Red',         'Thistle',
		    \	'Blue',           'ForestGreen', 'Mulberry',     'RedOrange',   'Turquoise',
		    \	'BlueGreen',      'Fuchsia',     'NavyBlue',     'RedViolet',   'Violet',
		    \	'BlueViolet',     'Goldenrod',   'OliveGreen',   'Rhodamine',   'VioletRed',
		    \	'BrickRed',       'Gray',        'Orange',       'RoyalBlue',   'White',
		    \	'Brown',          'Green',       'OrangeRed',    'RoyalPurple', 'WildStrawberry',
		    \	'BurntOrange',    'GreenYellow', 'Orchid',       'RubineRed',   'Yellow',
		    \	'CadetBlue',      'JungleGreen', 'Peach',        'Salmon',      'YellowGreen',
		    \	'CarnationPink',  'Lavender',    'Periwinkle',   'SeaGreen',    'YellowOrange',
		    \	'Cerulean',       'LimeGreen',   'PineGreen',    'Sepia',
		    \	'CornflowerBlue', 'Magenta',     'Plum',         'SkyBlue',
		    \ ]
    elseif line =~ '\\usepackage\[[^\]]*\<svgnames\*\?\>'
	let add_colors = [
		    \	'AliceBlue',      'DarkKhaki',      'Green',                'LightSlateGrey',
		    \	'AntiqueWhite',   'DarkMagenta',    'GreenYellow',          'LightSteelBlue',
		    \	'Aqua',           'DarkOliveGreen', 'Grey',                 'LightYellow',
		    \	'Aquamarine',     'DarkOrange',     'Honeydew',             'Lime',
		    \	'Azure',          'DarkOrchid',     'HotPink',              'LimeGreen',
		    \	'Beige',          'DarkRed',        'IndianRed',            'Linen',
		    \	'Bisque',         'DarkSalmon',     'Indigo',               'Magenta',
		    \	'Black',          'DarkSeaGreen',   'Ivory',                'Maroon',
		    \	'BlanchedAlmond', 'DarkSlateBlue',  'Khaki',                'MediumAquamarine',
		    \	'Blue',           'DarkSlateGray',  'Lavender',             'MediumBlue',
		    \	'BlueViolet',     'DarkSlateGrey',  'LavenderBlush',        'MediumOrchid',
		    \	'Brown',          'DarkTurquoise',  'LawnGreen',            'MediumPurple',
		    \	'BurlyWood',      'DarkViolet',     'LemonChiffon',         'MediumSeaGreen',
		    \	'CadetBlue',      'DeepPink',       'LightBlue',            'MediumSlateBlue',
		    \	'Chartreuse',     'DeepSkyBlue',    'LightCoral',           'MediumSpringGreen',
		    \	'Chocolate',      'DimGray',        'LightCyan',            'MediumTurquoise',
		    \	'Coral',          'DimGrey',        'LightGoldenrod',       'MediumVioletRed',
		    \	'CornflowerBlue', 'DodgerBlue',     'LightGoldenrodYellow', 'MidnightBlue',
		    \	'Cornsilk',       'FireBrick',      'LightGray',            'MintCream',
		    \	'Crimson',        'FloralWhite',    'LightGreen',           'MistyRose',
		    \	'Cyan',           'ForestGreen',    'LightGrey',            'Moccasin',
		    \	'DarkBlue',       'Fuchsia',        'LightPink',            'NavajoWhite',
		    \	'DarkCyan',       'Gainsboro',      'LightSalmon',          'Navy',
		    \	'DarkGoldenrod',  'GhostWhite',     'LightSeaGreen',        'NavyBlue',
		    \	'DarkGray',       'Gold',           'LightSkyBlue',         'OldLace',
		    \	'DarkGreen',      'Goldenrod',      'LightSlateBlue',       'Olive',
		    \	'DarkGrey',       'Gray',           'LightSlateGray',       'OliveDrab',
		    \	'Orange',        'Plum',        'Sienna',      'Thistle',
		    \	'OrangeRed',     'PowderBlue',  'Silver',      'Tomato',
		    \	'Orchid',        'Purple',      'SkyBlue',     'Turquoise',
		    \	'PaleGoldenrod', 'Red',         'SlateBlue',   'Violet',
		    \	'PaleGreen',     'RosyBrown',   'SlateGray',   'VioletRed',
		    \	'PaleTurquoise', 'RoyalBlue',   'SlateGrey',   'Wheat',
		    \	'PaleVioletRed', 'SaddleBrown', 'Snow',        'White',
		    \	'PapayaWhip',    'Salmon',      'SpringGreen', 'WhiteSmoke',
		    \	'PeachPuff',     'SandyBrown',  'SteelBlue',   'Yellow',
		    \	'Peru',          'SeaGreen',    'Tan',         'YellowGreen',
		    \	'Pink',          'Seashell',    'Teal',
		    \ ]
    elseif line =~ '\\usepackage\[[^\]]*\<x11names\*\?\>'
	let add_colors = [
		    \	'AntiqueWhite1', 'Chocolate3',      'DeepPink1',    'IndianRed3',
		    \ 	'AntiqueWhite2', 'Chocolate4',      'DeepPink2',    'IndianRed4',
		    \	'AntiqueWhite3', 'Coral1',          'DeepPink3',    'Ivory1',
		    \	'AntiqueWhite4', 'Coral2',          'DeepPink4',    'Ivory2',
		    \	'Aquamarine1',   'Coral3',          'DeepSkyBlue1', 'Ivory3',
		    \	'Aquamarine2',   'Coral4',          'DeepSkyBlue2', 'Ivory4',
		    \	'Aquamarine3',   'Cornsilk1',       'DeepSkyBlue3', 'Khaki1',
		    \	'Aquamarine4',   'Cornsilk2',       'DeepSkyBlue4', 'Khaki2',
		    \	'Azure1',        'Cornsilk3',       'DodgerBlue1',  'Khaki3',
		    \	'Azure2',        'Cornsilk4',       'DodgerBlue2',  'Khaki4',
		    \	'Azure3',        'Cyan1',           'DodgerBlue3',  'LavenderBlush1',
		    \	'Azure4',        'Cyan2',           'DodgerBlue4',  'LavenderBlush2',
		    \	'Bisque1',       'Cyan3',           'Firebrick1',   'LavenderBlush3',
		    \	'Bisque2',       'Cyan4',           'Firebrick2',   'LavenderBlush4',
		    \	'Bisque3',       'DarkGoldenrod1',  'Firebrick3',   'LemonChiffon1',
		    \	'Bisque4',       'DarkGoldenrod2',  'Firebrick4',   'LemonChiffon2',
		    \	'Blue1',         'DarkGoldenrod3',  'Gold1',        'LemonChiffon3',
		    \	'Blue2',         'DarkGoldenrod4',  'Gold2',        'LemonChiffon4',
		    \	'Blue3',         'DarkOliveGreen1', 'Gold3',        'LightBlue1',
		    \	'Blue4',         'DarkOliveGreen2', 'Gold4',        'LightBlue2',
		    \	'Brown1',        'DarkOliveGreen3', 'Goldenrod1',   'LightBlue3',
		    \	'Brown2',        'DarkOliveGreen4', 'Goldenrod2',   'LightBlue4',
		    \	'Brown3',        'DarkOrange1',     'Goldenrod3',   'LightCyan1',
		    \	'Brown4',        'DarkOrange2',     'Goldenrod4',   'LightCyan2',
		    \	'Burlywood1',    'DarkOrange3',     'Green1',       'LightCyan3',
		    \	'Burlywood2',    'DarkOrange4',     'Green2',       'LightCyan4',
		    \	'Burlywood3',    'DarkOrchid1',     'Green3',       'LightGoldenrod1',
		    \	'Burlywood4',    'DarkOrchid2',     'Green4',       'LightGoldenrod2',
		    \	'CadetBlue1',    'DarkOrchid3',     'Honeydew1',    'LightGoldenrod3',
		    \	'CadetBlue2',    'DarkOrchid4',     'Honeydew2',    'LightGoldenrod4',
		    \	'CadetBlue3',    'DarkSeaGreen1',   'Honeydew3',    'LightPink1',
		    \	'CadetBlue4',    'DarkSeaGreen2',   'Honeydew4',    'LightPink2',
		    \	'Chartreuse1',   'DarkSeaGreen3',   'HotPink1',     'LightPink3',
		    \	'Chartreuse2',   'DarkSeaGreen4',   'HotPink2',     'LightPink4',
		    \	'Chartreuse3',   'DarkSlateGray1',  'HotPink3',     'LightSalmon1',
		    \	'Chartreuse4',   'DarkSlateGray2',  'HotPink4',     'LightSalmon2',
		    \	'Chocolate1',    'DarkSlateGray3',  'IndianRed1',   'LightSalmon3',
		    \	'Chocolate2',    'DarkSlateGray4',  'IndianRed2',   'LightSalmon4',
		    \	'ghtSkyBlue1',   'Orange3',        'RosyBrown1',   'SpringGreen3',
		    \	'LightSkyBlue2',   'Orange4',        'RosyBrown2',   'SpringGreen4',
		    \	'LightSkyBlue3',   'OrangeRed1',     'RosyBrown3',   'SteelBlue1',
		    \	'LightSkyBlue4',   'OrangeRed2',     'RosyBrown4',   'SteelBlue2',
		    \	'LightSteelBlue1', 'OrangeRed3',     'RoyalBlue1',   'SteelBlue3',
		    \	'LightSteelBlue2', 'OrangeRed4',     'RoyalBlue2',   'SteelBlue4',
		    \	'LightSteelBlue3', 'Orchid1',        'RoyalBlue3',   'Tan1',
		    \	'LightSteelBlue4', 'Orchid2',        'RoyalBlue4',   'Tan2',
		    \	'LightYellow1',    'Orchid3',        'Salmon1',      'Tan3',
		    \	'LightYellow2',    'Orchid4',        'Salmon2',      'Tan4',
		    \	'LightYellow3',    'PaleGreen1',     'Salmon3',      'Thistle1',
		    \	'LightYellow4',    'PaleGreen2',     'Salmon4',      'Thistle2',
		    \	'Magenta1',        'PaleGreen3',     'SeaGreen1',    'Thistle3',
		    \	'Magenta2',        'PaleGreen4',     'SeaGreen2',    'Thistle4',
		    \	'Magenta3',        'PaleTurquoise1', 'SeaGreen3',    'Tomato1',
		    \	'Magenta4',        'PaleTurquoise2', 'SeaGreen4',    'Tomato2',
		    \	'Maroon1',         'PaleTurquoise3', 'Seashell1',    'Tomato3',
		    \	'Maroon2',         'PaleTurquoise4', 'Seashell2',    'Tomato4',
		    \	'Maroon3',         'PaleVioletRed1', 'Seashell3',    'Turquoise1',
		    \	'Maroon4',         'PaleVioletRed2', 'Seashell4',    'Turquoise2',
		    \	'MediumOrchid1',   'PaleVioletRed3', 'Sienna1',      'Turquoise3',
		    \	'MediumOrchid2',   'PaleVioletRed4', 'Sienna2',      'Turquoise4',
		    \	'MediumOrchid3',   'PeachPuff1',     'Sienna3',      'VioletRed1',
		    \	'MediumOrchid4',   'PeachPuff2',     'Sienna4',      'VioletRed2',
		    \	'MediumPurple1',   'PeachPuff3',     'SkyBlue1',     'VioletRed3',
		    \	'MediumPurple2',   'PeachPuff4',     'SkyBlue2',     'VioletRed4',
		    \	'MediumPurple3',   'Pink1',          'SkyBlue3',     'Wheat1',
		    \	'MediumPurple4',   'Pink2',          'SkyBlue4',     'Wheat2',
		    \	'MistyRose1',      'Pink3',          'SlateBlue1',   'Wheat3',
		    \	'MistyRose2',      'Pink4',          'SlateBlue2',   'Wheat4',
		    \	'MistyRose3',      'Plum1',          'SlateBlue3',   'Yellow1',
		    \	'MistyRose4',      'Plum2',          'SlateBlue4',   'Yellow2',
		    \	'NavajoWhite1',    'Plum3',          'SlateGray1',   'Yellow3',
		    \	'NavajoWhite2',    'Plum4',          'SlateGray2',   'Yellow4',
		    \	'NavajoWhite3',    'Purple1',        'SlateGray3',   'Gray0',
		    \	'NavajoWhite4',    'Purple2',        'SlateGray4',   'Green0',
		    \	'OliveDrab1',      'Purple3',        'Snow1',        'Grey0',
		    \	'OliveDrab2',      'Purple4',        'Snow2',        'Maroon0',
		    \	'OliveDrab3',      'Red1',           'Snow3',        'Purple0',
		    \ 	'OliveDrab4',      'Red2',           'Snow4',
		    \ 	'Orange1',         'Red3',           'SpringGreen1',
		    \ 	'Orange2',         'Red4',           'SpringGreen2'
		    \ ]
    else
	let add_colors=[]
    endif
    call extend(colors, add_colors)
    return colors
endfunction
ftplugin/ATP_files/project.vim	[[[1
824
" Author: 	Marcin Szamotulski
" Description: 	A vim script which stores values of variables in a project script.
" 		It is read, and written via autocommands.
" Note:		This file is a part of Automatic Tex Plugin for Vim.
" Language:	tex
" Last Change:Tue Sep 06, 2011 at 03:17  +0100

let s:sourced 	= exists("s:sourced") ? 1 : 0

" VARIABLES:
" Variables {{{

" If the user set g:atp_RelativePath
" if exists("g:atp_RelativePath") && g:atp_RelativePath
"     setl noautochdir
" endif

let s:file	= expand('<sfile>:p')

" This gives some debug info: which project scripts are loaded, loading time,
" which project scripts are written.
" Debug File: /tmp/ATP_ProjectScriptDebug.vim  / only for s:WriteProjectScript() /
if !exists("g:atp_debugProject")
    let g:atp_debugProject 	= 0
endif
if !exists("g:atp_debugLPS")
    " debug <SID>LoadProjectScript (project.vim)
    let g:atp_debugLPS		= 0
endif
if !exists("g:atp_RelativePath")
    let g:atp_RelativePath 	= 1
endif
" Also can be set in vimrc file or atprc file! (tested)
" The default value (0) is set in options.vim
if !exists("g:atp_TempDir")
    call atplib#TempDir()
endif

" Windows version:
let s:windows	= has("win16") || has("win32") || has("win64") || has("win95")

" This variable is set if the projectr script was loaded by s:LoadScript()
" function.
" s:project_Load = { type : 0/1 }

if !exists("s:project_Load")
    " Load once in s:LoadScript() function
    let s:project_Load	= {}
    let g:project_Load	= s:project_Load
endif
if !exists("g:atp_CommonScriptDirectory")
    let g:atp_CommonScriptDirectory	= expand('<sfile>:p:h')
endif
if !isdirectory(g:atp_CommonScriptDirectory)
    " Make common script dir if it doesn't exist (and all intermediate directories).
    call mkdir(g:atp_CommonScriptDirectory, "p")
endif

" Mimic names of vim view files
let s:common_project_script	= s:windows ? g:atp_CommonScriptDirectory  . '\common_var.vim' : g:atp_CommonScriptDirectory . '/common_var.vim' 

" These local variables will be saved:
" let g:atp_ProjectGlobalVariable = [ 
" 	    \ 'b:atp_MainFile',
" 	    \ 'b:atp_ProjectScript',
" 	    \ 'b:atp_LocalCommands', 		'b:atp_LocalEnvironments', 
" 	    \ 'b:atp_LocalColors',
" 	    \ 'b:TreeOfFiles', 			'b:ListOfFiles', 
" 	    \ 'b:TypeDict', 			'b:LevelDict', 
" 	    \ 'b:atp_StarEnvDefault', 		'b:atp_StarMathEnvDefault',
" 	    \ ]
" Note: b:atp_ProjectDir is not here by default by the following reason: it is
" specific to the host, without it sharing the project file is possible.
" b:atp_PackageList is another variable that could be put into project script.

" This are common variable to all tex files.
let g:atp_ProjectGlobalVariables = [ 'g:atp_LatexPackages', 'g:atp_LatexClasses', 'g:atp_Library' ]
" }}}

" AUTOCOMMANDS:
augroup ATP_ProjectFile
    au!
    au BufEnter *.tex.project.vim if has("persistent_undo") | setlocal noundofile | endif
augroup END

" FUNCTIONS: (soure once)
if !s:sourced || g:atp_reload_functions "{{{
" LOAD PROJECT SCRIPT:
"{{{ s:LoadScript(), FindProjectScripts(), GetProjectScript(), s:LoadProjectScript()
" s:LoadScript({bang}, {project_script}, {type}, {load_variables}, [silent], [ch_load])
"
" a:bang == "!" ignore texmf tree and ignore b:atp_ProjectScript, g:atp_ProjectScript
" variables
" a:project_script	file to source 
" a:type = 'local'/'global'
" a:load_variabels	load variables after loading project script	
" 			can be used on startup to load variables which depend
" 			on things set in project script.
" a:1 = 'silent'/'' 	echo messages
" a:2 = ch_load		check if project script was already loaded
" a:3 = ignore		ignore b:atp_ProjectScript and g:atp_ProjectScript variables
" 				used by commands
function! <SID>LoadScript(bang, project_script, type, load_variables, ...) "{{{

    if g:atp_debugProject
	exe "redir! > ".g:atp_TempDir."/LoadScript.log"
	let hist_time	= reltime()
	echomsg "ATP_ProjectScript: LoadScript " . a:type . " file " . string(a:project_script)
    endif

    let silent	= a:0 >= 1 ? a:1 : "0"
    let silent 	= silent || silent == "silent" ? "silent" : ""
    let ch_load = a:0 >= 2 ? a:2 : 0 
    let ignore	= a:0 >= 3 ? a:3 : 0

    " Is project script on/off
    " The local variable overrides the global ones!

    " Note:
    " When starting the vim b:atp_ProjectScript might not be yet defined (will be
    " defined later, and g:atp_ProjectScript might already be defined, so not always
    " global variables override local ones).

    " Global variable overrides local one
    if !ignore && ( exists("g:atp_ProjectScript") && !g:atp_ProjectScript || exists("b:atp_ProjectScript") && ( !b:atp_ProjectScript && (!exists("g:atp_ProjectScript") || exists("g:atp_ProjectScript") && !g:atp_ProjectScript )) )
	exe silent . ' echomsg "[ATP:] LoadScirpt: not loading project script."'

	if g:atp_debugProject
	    echomsg "b:atp_ProjectScript=" . ( exists("b:atp_ProjectScript") ? b:atp_ProjectScript : -1 ) . " g:atp_ProjectScript=" . ( exists("g:atp_ProjectScript") ? g:atp_ProjectScript : -1 ) . "\n"
	    echomsg "ATP_ProjectScript : END " !ignore
	    redir END
	endif
	return
    endif

    " Load once feature (if ch_load)	- this is used on starup
    if ch_load && get(get(s:project_Load, expand("%:p"), []), a:type, 0) >= 1
	silent echomsg "[ATP:]  " . a:type . "project script already loaded for buffer " . expand("%:p") . "."
	if g:atp_debugProject
	    redir END
	endif
	return
    endif

    let cond_A	= get(s:project_Load, expand("%:p"), {}) != {}
    let cond_B	= get(get(s:project_Load, expand("%:p"), []), a:type, 0)
    if empty(expand("%:p"))
	if g:atp_debugProject
	    echohl ErrorMsg
	    echomsg "[ATP LoadProjectScript:] Error : File name is empty. Not loading project script."
	    echohl None
	    redir END
	endif
	return
    endif
    if cond_B
	let s:project_Load[expand("%:p")][a:type][0] += 1 
    elseif cond_A
	call extend(s:project_Load[expand("%:p")], { a:type : 1 })
    else
	let s:project_Load= { expand("%:p") : { a:type : 1 } }
    endif

    if a:bang == "" && expand("%:p") =~ 'texmf' 
	if g:atp_debugProject
	    redir END
	endif
	return
    endif

    let b:atp_histloaded=1
    if a:type == "local"
	let save_loclist = getloclist(0)
	try
	    silent exe 'lvimgrep /^[^"]*\Clet\s\+b:atp_ProjectScript\>\s*=/j ' . fnameescape(a:project_script)
	catch /E480:/
	endtry
	let loclist = getloclist(0)
	execute get(get(loclist, 0, {}), 'text', "")
	if exists("b:atp_ProjectScript") && !b:atp_ProjectScript
	    if g:atp_debugProject
		silent echomsg "[ATP:] ATP_ProjectScript: b:atp_ProjectScript == 0 in the project script."
		redir END
	    endif
	    return
	endif
	call setloclist(0,[])
	try 
	    silent exe 'lvimgrep /^\s*\(set\?\|setl\%[ocal]\)\s/j ' . fnameescape(a:project_script)
	catch /E480:/
	endtry

	" Find all the vim options:
	let b:atp_vim_settings = map(getloclist(0), "v:val['text']")
	" This variable is used by ATP_LoadVimSettings() (augroup
	" ATP_LoadVimSettings) where it is deleted.
	call setloclist(0, save_loclist)
    endif

    " Load first b:atp_ProjectScript variable
    try
	if filereadable(a:project_script)
	    execute "silent! source " . fnameescape(a:project_script)
	endif

	if g:atp_debugProject
	    echomsg "[ATP:] ATP_ProjectScript: sourcing " . a:project_script
	endif
    catch /E484:/
    endtry

    if g:atp_debugProject
	echomsg "[ATP:] ATP_ProjectScript: sourcing time: " . reltimestr(reltime(hist_time))
	redir! END
    endif

    if a:load_variables
	if !exists("b:atp_project")
	    if exists("b:LevelDict") && max(values(filter(deepcopy(b:LevelDict), "get(b:TypeDict, v:key, '')=='input'"))) >= 1
		let b:atp_project	= 1
	    else
		let b:atp_project 	= 0
	    endif
	endif
    endif

"     if a:type == 'local'
" 	call <SID>TEST()
"     endif
endfunction "}}}
" This functoin finds recursilevy (upward) all project scripts. 
" {{{ FindProjectScripts()
function! FindProjectScripts()
    let dir 	= fnamemodify(resolve(expand("%:p")), ":p:h")
    let cwd 	= getcwd()
    try
	exe "lcd " . fnameescape(dir)
    catch /E344:/
	return [] 
    endtry
    while glob('*.project.vim', 1) == '' 
	let dir_l 	= dir
	let dir 	= fnamemodify(dir, ":h")
	if dir == $HOME || dir == dir_l
	    break
	endif
	exe "lcd " . fnameescape(dir)
    endwhile
    let project_files = map(split(glob('*project.vim', 1), "\n"), "fnamemodify(v:val, \":p\")")
    exe "lcd " . fnameescape(cwd)
    return project_files
endfunction "}}}
" This function looks to which project current buffer belongs.
" {{{ GetProjectScript(project_files)
" a:project_files = FindProjectScripts()
function! GetProjectScript(project_files)
    for pfile in a:project_files
	if g:atp_debugLPS
	    echomsg "[ATP:] checking " . pfile 
	endif
	let save_loclist 	= getloclist(0)
	let file_name 	= s:windows ? escape(expand("%:p"), '\') : escape(expand("%:p"), '/') 
	let sfile_name 	= expand("%:t")
	try
	    if !g:atp_RelativePath
		exe 'lvimgrep /^\s*let\s\+\%(b:atp_MainFile\s\+=\s*\%(''\|"\)\%(' . file_name . '\|' . sfile_name . '\)\>\%(''\|"\)\|b:ListOfFiles\s\+=.*\%(''\|"\)' . file_name . '\>\)/j ' . fnameescape(pfile)
	    else
		exe 'lvimgrep /^\s*let\s\+\%(b:atp_MainFile\s\+=\s*\%(''\|"\)[^''"]*\<\%(' . sfile_name . '\)\>\%(''\|"\)\|b:ListOfFiles\s\+=.*\%(''\|"\)[^''"]*\<' . sfile_name . '\>\)/j ' . fnameescape(pfile)
	    endif
	catch /E480:/ 
	    if g:atp_debugProject
		silent echomsg "[ATP:] script file " . pfile . " doesn't match."
	    endif
	endtry
	let loclist	= getloclist(0)
	if len(loclist) 
	    let bufnr 	= get(get(loclist, 0, {}), 'bufnr', 'no match')
	    if bufnr != 'no match'
		let project_script 	= fnamemodify(bufname(bufnr), ":p")
	    endif
	    return project_script
	endif
    endfor
    return "no project script found"
endfunction "}}}
" This function uses all three above functions: FindProjectScripts(),
" GetProjectScript() and <SID>LoadScript()
" {{{ <SID>LoadProjectScript
" Note: bang has a meaning only for loading the common project script.
function! <SID>LoadProjectScript(bang,...)

    if ( exists("g:atp_ProjectScript") && !g:atp_ProjectScript || exists("b:atp_ProjectScript") && ( !b:atp_ProjectScript && (!exists("g:atp_ProjectScript") || exists("g:atp_ProjectScript") && !g:atp_ProjectScript )) )
	exe "redir! > ".g:atp_TempDir."/LoadProjectScript.log"
	silent echo "+++ SKIPPING : LOAD PROJECT SCRIPT +++"
	redir END
	return
    endif

    let local = (a:0 >= 1 ? a:1 : 'local' )
    if g:atp_debugLPS
	let time = reltime()
    endif

    if local == 'global' || local == 'common' 
	call s:LoadScript(a:bang,s:common_project_script, 'global', 0, '', 1)
	if g:atp_debugLPS
	    let g:LPS_time = reltimestr(reltime(time))
	    echomsg "Load Project Script time (common): " . g:LPS_time
	endif
	return
    endif

    if !exists("b:atp_ProjectScriptFile")
	" Look for the project file
" 	echo join(project_files, "\n")
	let project_files = FindProjectScripts()

	" Return if nothing was found
	if len(project_files) == 0
	    let b:atp_ProjectScriptFile = resolve(expand("%:p")) . ".project.vim"
	    let b:atp_ProjectDir	= fnamemodify(b:atp_ProjectScriptFile, ":h")
	    return
	endif

	" Move project_file corresponding to the current buffer to the first
	" place if it exists.
	" This saves time :) when there are many project files
	" (especially when the projects are big)
	let index 	= index(project_files, expand("%:p") . ".project.vim")
	if index != -1
	    call remove(project_files, index)
	    call extend(project_files, [ expand("%:p") . ".project.vim" ], 0) 
	endif

	let save_loclist = getloclist(0)
	call setloclist(0, [])


	let project_script = GetProjectScript(project_files)
	if project_script != "no project script found"
	    if g:atp_debugLPS
		echomsg "Loading  " . project_script 
	    endif
	    call <SID>LoadScript("", project_script, "local", 0, "silent", 1, 0)
	    let b:atp_ProjectScriptFile = project_script
	    let b:atp_ProjectDir	= fnamemodify(b:atp_ProjectScriptFile, ":h")
	else
	    " If there was no project script we set the variable and it will
	    " be written when quiting vim by <SID>WriteProjectScript().
	    let b:atp_ProjectScriptFile = resolve(expand("%:p")) . ".project.vim"
	    let b:atp_ProjectDir	= fnamemodify(b:atp_ProjectScriptFile, ":h")
	    return
	endif
    else
	try
	execute "silent! source " . fnameescape(b:atp_ProjectScriptFile)
	let b:atp_ProjectDir	= fnamemodify(b:atp_ProjectScriptFile, ":h")
	catch /E484/
	    " this is used by the s:Babel() function.
	    " if b:atp_ProjectDir is unset it returns.
	    unlet b:atp_ProjectDir
	endtry
    endif

    if g:atp_debugLPS
	let g:LPS_time = reltimestr(reltime(time))
	echomsg "LPS time: " . g:LPS_time
    endif
endfunction
function! s:LocalCommonComp(ArgLead, CmdLine, CursorPos)
    return filter([ 'local', 'common'], 'v:val =~ "^" . a:ArgLead')
endfunction
" }}}
" LoadVimSettings "{{{
function! ATP_LoadVimSettings()
    " Load Vim settings stored in project script file (.tex.project.vim)
    if !exists("b:atp_vim_settings")
	return
    endif
    for line in b:atp_vim_settings
	exe line
    endfor
    " In this way options are loaded only once:
    unlet b:atp_vim_settings
endfunction "}}}
"}}}
" WRITE PROJECT SCRIPT:
"{{{ s:WriteProjectScript(), :WriteProjectScript, autocommands
" This function writes the project file but only if there there are changes.
" This is so, because writing very long lines is much slower than reading (it
" reads the file and compare the variables with the existing ones).
try
function! <SID>WriteProjectScript(bang, project_script, cached_variables, type, ...)

    "Do not echo messages
    let silent = ( a:0 > 0 ? a:1 : 0 )

    if g:atp_debugProject
	let g:project_script = a:project_script
	let g:type = a:type
    endif

    if !exists("b:ListOfFiles")
	let atp_MainFile	= atplib#FullPath(b:atp_MainFile)
	call TreeOfFiles(atp_MainFile)
    endif

    if g:atp_debugProject
	exe "redir! > ".g:atp_TempDir."/WriteProjectScript.log"
	echomsg "ATP_ProjectScript: WriteProjectScript " . a:type
	let time = reltime()
    endif

    " If none of the variables exists -> return
    let exists=max(map(deepcopy(a:cached_variables), "exists(v:val)")) 
    if !exists
	if g:atp_debugProject
	    echomsg "no variable exists"
	endif
	if g:atp_debugProject >= 2
	    echomsg "Write Project Script time " . reltimestr(reltime(time))
	endif
	return
    endif

    if a:bang == "" && expand("%:p") =~ 'texmf'
	if g:atp_debugProject
	    echomsg "texmf return"
	endif
	if g:atp_debugProject
	    let g:return = 1
	endif
	if g:atp_debugProject >= 2
	    echomsg "Write Project Script time " . reltimestr(reltime(time))
	endif
	return
    endif

    " a:bang == '!' then force to write project script even if it is turned off
    " localy or globaly.
    " The global variable overrides the local one!
    let cond = exists("g:atp_ProjectScript") && !g:atp_ProjectScript || exists("b:atp_ProjectScript") && ( !b:atp_ProjectScript && (!exists("g:atp_ProjectScript") || exists("g:atp_ProjectScript") && !g:atp_ProjectScript )) || !exists("b:atp_ProjectScript") && !exists("g:atp_ProjectScript")
    if  a:bang == "" && cond
	if !silent
	    echomsg "[ATP:] WriteProjectScript: ProjectScript is turned off."
	endif
	if g:atp_debugProject
	    redir END
	endif
	if g:atp_debugProject
	    let g:return = 2
	endif
	if g:atp_debugProject >= 2
	    echomsg "Write Project Script time " . reltimestr(reltime(time))
	endif
	return
    endif

    let winsaveview	= winsaveview()

    " Check if global variables where changed.
    " (1) copy global variable to l:variables
    " 	  and remove defined global variables.
    " (2) source the project script and compare the results.
    " (3) resore variables and write the project script.
    if a:type == "global"
	let existing_variables 	= {}
	for var in a:cached_variables 
	    if g:atp_debugProject >= 2
		echomsg var . " EXISTS " . exists(var)
	    endif

	    " step (1) copy variables
	    let lvar = "l:" . substitute(var, '^[bg]:', '', '')
	    if exists(var)
		call extend(existing_variables, { var : string({var}) })
		exe "let " . lvar . "=" .  string({var})
		exe "unlet " . var
	    endif
	endfor
	" step (2a) source project script
	if filereadable(a:project_script)
	    execute "source " . fnameescape(a:project_script)
	endif
	let cond = 0
	for var in a:cached_variables
	    let lvar = "l:" . substitute(var, '^[bg]:', '', '')
	    " step (2b) check if variables have changed
	    if exists(var) && exists(lvar)
		let cond_A = ({lvar} != {var})
		if g:atp_debugProject
		    echomsg var . " and " . lvar . " exist. cond_A=" . cond_A 
		endif
		let cond += cond_A
		if cond_A
		    let {var} = {lvar}
		endif
	    elseif !exists(var) && exists(lvar)
		if g:atp_debugProject
		    echomsg var . " nexists but " . lvar . " exist."
		endif
		let {var} = {lvar}
		let cond += 1
	    elseif exists(var) && !exists(lvar)
		if g:atp_debugProject
		    echomsg var . " exists and " . lvar . " nexist."
		endif
		unlet {var}
		let cond += 1
	    else
		if g:atp_debugProject
		    echomsg var . " and " . lvar . " nexist."
		endif
	    endif
	endfor

	if g:atp_debugProject
	    let g:cond_global = cond
	    echomsg "cond " . cond
	endif

	" step (3a) copy variables from local ones.
	for var in g:atp_ProjectGlobalVariables
	    let lvar = "l:" . substitute(var, '^[bg]:', '', '')
	    if g:atp_debugProject
		echomsg "(3a) " . var . " exists " . lvar . " " . ( exists(lvar) ? 'exists' : 'nexists' )
	    endif
	    if exists(lvar)
		if g:atp_debugProject
		    echomsg "(3a) Restoring " . var . " from " . lvar
		endif
		try
		    let {var} = {lvar}
		catch /E741:/ 
		    exe "unlockvar " . var
		    let {var} = {lvar}
		    exe "lockvar " . var
		endtry
	    endif
	endfor

	if cond == 0
	    if g:atp_debugProject
		silent echomsg "Project script not changed " . "\n"
		silent echo "Write Project Script time = " . reltimestr(reltime(time)) . "\n"
	    endif
	    if g:atp_debugProject
		let g:return = 3
	    endif
	    if g:atp_debugProject >= 2
		echomsg "Write Project Script time " . reltimestr(reltime(time))
	    endif
	    return
	endif
    endif
    
    " Make a list of variables defined in project script
    let defined_variables	= []
    let save_loclist		= getloclist(0)
    try
	silent! exe 'lvimgrep /^\s*\<let\>\s\+[bg]:/j ' . fnameescape(a:project_script)
    catch /^Vim\%((\a\+)\)\=:E480/
    catch /^Vim\%((\a\+)\)\=:E486/
    catch /^Vim\%((\a\+)\)\=:E21/
    endtry
    let defined_variables	= getloclist(0) 
    call map(defined_variables, 'matchstr(v:val["text"], ''^\s*let\s\+\zs[bg]:[^[:blank:]=]*'')') 
    call setloclist(0, save_loclist) 
    if g:atp_debugProject
	let g:defined_variables	= defined_variables
    endif


    let deleted_variables	= []
    for var in defined_variables
	if !exists(var)
	    call add(deleted_variables, var)
	endif
    endfor

    if g:atp_debugProject
	let g:existing_variables	= []
    endif
    for var in a:cached_variables
	if exists(var)
	    let lvar	= 'l:' . substitute(var, '^[bg]:', '', '')
	    let {lvar} = {var}
	    if g:atp_debugProject
		call add(g:existing_variables, var)
	    endif
	endif
    endfor

    if g:atp_debugProject
	let g:deleted_variables = deleted_variables
    endif

    let hidden	= &l:hidden
    setl hidden

    let lazyredraw = &l:lazyredraw
    setl lazyredraw

    let bufnr	= bufnr("%")
    try
	silent! exe "keepalt keepjumps edit +setl\\ noswapfile " . fnameescape(a:project_script)
    catch /.*/
	echoerr v:errmsg
	let errmsg	= v:errmsg
	echoerr "WriteProjectScript catched error while opening " . a:project_script . ". Project script not written."
	let v:errmsg	= errmsg
	let &l:hidden		= hidden
	let &l:lazyredraw	= lazyredraw
	if g:atp_debugProject
	    let g:return = 4
	endif
	if g:atp_debugProject >= 2
	    echomsg "Write Project Script time " . reltimestr(reltime(time))
	endif
	return 
    endtry
    if has("persistent_undo")
	setl noundofile
    endif

    " Delete the variables which where unlet:
    for var in deleted_variables
	try 
	    exe 'keepjumps silent! %g/^\s*let\s\+' . var . '\>/d_'
	catch /E48\%(6\|0\):/
	endtry
    endfor

    " Write new variables:
    for var in a:cached_variables

	let lvar 	=  "l:" . substitute(var, '^[bg]:', '', '')
	    if g:atp_debugProject
		echomsg var . " " . exists(lvar)
	    endif

	if exists(lvar)

	    try 
		exe 'silent! keepjumps %g/^\s*let\s\+' . var . '\>/d_'
	    catch /^Vim\%((\a\+)\)\=:E486/
	    catch /^Vim\%((\a\+)\)\=:E21/
	    endtry
	    keepjumps call append('$', 'let ' . var . ' = ' . string({lvar}))
	endif
    endfor
    " Save project script file:
    if getline(1) !~# '" ATP project vim script'
	call append(0, '" ATP project vim script: '.strftime( "%a %b %d, %Y at %I:%M %p %z").".")
    endif
    silent write
    let projectscript_bufnr	= bufnr("%")
    exe "silent keepalt keepjumps b " . bufnr
    exe "bdelete " . projectscript_bufnr


    let &l:lazyredraw = lazyredraw
    call winrestview(winsaveview)

    if g:atp_debugProject
	silent echo "Write Project Script time = " . reltimestr(reltime(time))
	redir END
    endif
    if g:atp_debugProject >= 2
	echomsg "Write Project Script time " . reltimestr(reltime(time))
    endif
endfunction
catch /E127:/
endtry
function! <SID>WriteProjectScriptInterface(bang,...)
    let type 	= ( a:0 >= 1 ? a:1 : 'local' )
    let silent  = ( a:0 >= 2 ? a:2 : 0 )

    if type != 'global' && type != 'local' 
	echoerr "WriteProjectScript Error : type can be: local or global." 
	return
    endif

    let script 	= ( type == 'local' ? b:atp_ProjectScriptFile : s:common_project_script )
    let variables = ( type == 'local' ? g:atp_ProjectLocalVariables : g:atp_ProjectGlobalVariables )
    if type == 'local' && !silent
	echomsg "[ATP:] writing to " . b:atp_ProjectScriptFile
    endif
    call s:WriteProjectScript(a:bang, script, variables, type, silent)
endfunction
function! s:WPSI_comp(ArgLead, CmdLine, CursorPos)
    return filter(['local', 'global'], 'v:val =~ a:ArgLead')
endfunction 
"{{{ WriteProjectScript AUTOCOMMANDS:
function! <SID>AU_WriteLocalProjectScript()
    if &filetype =~ 'tex' &&
	    \ !( exists("g:atp_ProjectScript") && !g:atp_ProjectScript || exists("b:atp_ProjectScript") && ( !b:atp_ProjectScript && (!exists("g:atp_ProjectScript") || exists("g:atp_ProjectScript") && !g:atp_ProjectScript )) )
	call s:WriteProjectScript("", b:atp_ProjectScriptFile, g:atp_ProjectLocalVariables, 'local', 1)
    endif
endfunction
function! <SID>AU_WriteGlobalProjectScript()
    if &filetype =~ 'tex' &&
	    \ !( exists("g:atp_ProjectScript") && !g:atp_ProjectScript || exists("b:atp_ProjectScript") && ( !b:atp_ProjectScript && (!exists("g:atp_ProjectScript") || exists("g:atp_ProjectScript") && !g:atp_ProjectScript )) )
	call s:WriteProjectScript("", s:common_project_script, g:atp_ProjectGlobalVariables, 'global', 1)
    endif
endfunction
augroup ATP_WriteProjectScript 
    au!
    " Before it was VimLeave, write silently.
    au BufUnload *.tex call <SID>AU_WriteLocalProjectScript()
    au BufUnload *.tex call <SID>AU_WriteGlobalProjectScript()
augroup END 
"}}}
"}}}
" SET PROJECT SCRIPT: on/off
" {{{ s:ProjectScript
function! <SID>ProjectScript(...)
    let arg = ( a:0 >=1 ? a:1 : "" )
    if arg == ""
	let b:atp_ProjectScript=!b:atp_ProjectScript
    elseif arg == "on"
	let b:atp_ProjectScript=1
	:WriteProjectScript!
    elseif arg == "off"
	let b:atp_ProjectScript=0
	:WriteProjectScript!
    endif
    if b:atp_ProjectScript
	echomsg "[ATP:] Project Script - ON."
    else
	echomsg "[ATP:] Project Script - OFF."
    endif
    return b:atp_ProjectScript
endfunction
function! HistComp(ArgLead, CmdLine, CursorPos)
    return filter(['on', 'off'], 'v:val =~ a:ArgLead')
endfunction "}}}

" DELETE PROJECT SCRIPT:
" s:DeleteProjectScript {{{
" 	It has one argument a:1 == "local" or " a:0 == 0 " delete the		 
" 	b:atp_ProjectScriptFile.
" 	otherwise delete s:common_project_script.  With bang it forces to delete the
" 	s:common_project_script" 
" 	It also unlets the variables stored in s:common_project_script.
function! <SID>DeleteProjectScript(bang,...) 
    let type	= ( a:0 >= 1 ? a:1 : "local" )

    if type == "local"
	let file = b:atp_ProjectScriptFile
    else
	let file = s:common_project_script
    endif

    call delete(file)
    echo "[ATP:] Project Script ".file." deleted."
    if type == "local" && a:bang == "!"
	let file = s:common_project_script
	call delete(file)
	echo "[ATP:] Project Script ".file." deleted."
    endif
    if file == s:common_project_script
	for var in g:atp_ProjectGlobalVariables
	    exe "unlet " . var
	endfor
    endif
endfunction
function! s:DelPS(CmdArg, CmdLine, CursorPos)
    let comp	= [ "local", "common" ]  
    call filter(comp, "v:val =~ '^' . a:CmdArg")
    return comp
endfunction
" Show ProjectScript:
" function! <SID>ShowProjectScript(bang)
" 
"     let history_file
" endfunction
" }}}

" Save and Restore Project Variables (used by atplib#motion#GotoFile()).
function! SaveProjectVariables(...) "{{{
    let variables_List	= ( a:0 >= 1 ? {a:1} : g:atp_SavedProjectLocalVariables )
    let variables_Dict 	= {}
    for var in variables_List
	if exists(var)
	    call extend(variables_Dict, { var : {var} })
	endif
    endfor
    return variables_Dict
endfunction "}}}
function! RestoreProjectVariables(variables_Dict) "{{{
    for var in keys(a:variables_Dict)
 	let cmd =  "let " . var . "=" . string(a:variables_Dict[var])
	try
	    exe cmd
	catch E741:
	    " if the variable was locked:
	    exe "unlockvar ".var
	    exe cmd
	    exe "lockvar ".var 
	endtry
    endfor
endfunction "}}}
endif "}}}

" SCRIPT:
" (includes commands, and maps - all the things 
" 		that must be sources for each file)
" {{{
call <SID>LoadProjectScript("", "local")
" Project script should by loaded now, and not by autocommands which are executed after
" sourcing scripts. In this way variables set in project script will be used
" when sourcing other atp scripts.
call s:LoadScript("", s:common_project_script, 'global', 0, 'silent',1)

" Commands:
command! -buffer -bang -nargs=? -complete=customlist,s:LocalCommonGlobalComp LoadProjectScript :call <SID>LoadProjectScript(<q-bang>,<f-args>)
" write:
command! -buffer -bang -nargs=? -complete=customlist,s:WPSI_comp WriteProjectScript	:call <SID>WriteProjectScriptInterface(<q-bang>,<f-args>)
command! -buffer -nargs=* -complete=customlist,HistComp 	ProjectScript 		:call <SID>ProjectScript(<f-args>)

" delete:
command! -buffer -bang -complete=customlist,s:DelPS -nargs=? 	DeleteProjectScript 	:call s:DeleteProjectScript(<q-bang>, <f-args>)
" }}}
ftplugin/ATP_files/search.vim	[[[1
103
" Author:	Marcin Szamotulski
" Description:  This file provides searching tools of ATP.
" Note:		This file is a part of Automatic Tex Plugin for Vim.
" Language:	tex
" Last Change:

let s:sourced 	= exists("s:sourced") ? 1 : 0
 
" Functions:
" Find all names of locally defined commands, colors and environments. 
" Used by the completion function.
" {{{ LocalCommands
function! LocalCommands(write, ...)
    let time=reltime()
    let pattern = a:0 >= 1 && a:1 != '' ? a:1 : '\\def\>\|\\newcommand\>\|\\newenvironment\|\\newtheorem\|\\definecolor\|'
		\ . '\\Declare\%(RobustCommand\|FixedFont\|TextFontCommand\|MathVersion\|SymbolFontAlphabet'
			    \ . '\|MathSymbol\|MathDelimiter\|MathAccent\|MathRadical\|MathOperator\)'
		\ . '\|\\SetMathAlphabet\>'
    let bang	= a:0 >= 2 ? a:2 : '' 

    if has("python") && ( !exists("g:atp_no_python") || g:atp_no_python == 0 )
	call atplib#search#LocalCommands_py(a:write, '' , bang)
    else
	call atplib#search#LocalCommands_vim(pattern, bang)
    endif
    if !(exists("g:atp_no_local_abbreviations") && g:atp_no_local_abbreviations == 1)
	call atplib#search#LocalAbbreviations()
    endif
    let g:time_LocalCommands=reltimestr(reltime(time))
endfunction
" }}}

" BibSearch:
"{{{ variables
let g:bibentries=['article', 'book', 'booklet', 'conference', 'inbook', 'incollection', 'inproceedings', 'manual', 'mastertheosis', 'misc', 'phdthesis', 'proceedings', 'techreport', 'unpublished']

let g:bibmatchgroup		='String'
let g:defaultbibflags		= 'tabejsyu'
let g:defaultallbibflags	= 'tabejfsvnyPNSohiuHcp'
let b:lastbibflags		= g:defaultbibflags	" Set the lastflags variable to the default value on the startup.
let g:bibflagsdict=atplib#bibsearch#bibflagsdict
" These two variables were s:... but I switched to atplib ...
let g:bibflagslist		= keys(g:bibflagsdict)
let g:bibflagsstring		= join(g:bibflagslist,'')
let g:kwflagsdict={ 	  '@a' : '@article', 	
	    		\ '@b' : '@book\%(let\)\@<!', 
			\ '@B' : '@booklet', 	
			\ '@c' : '@in\%(collection\|book\)', 
			\ '@m' : '@misc', 	
			\ '@M' : '@manual', 
			\ '@p' : '@\%(conference\)\|\%(\%(in\)\?proceedings\)', 
			\ '@t' : '@\%(\%(master)\|\%(phd\)\)thesis', 
			\ '@T' : '@techreport', 
			\ '@u' : '@unpublished' }    

"}}}

" Mappings:
nnoremap <silent> <Plug>BibSearchLast		:call atplib#search#BibSearch("", b:atp_LastBibPattern, b:atp_LastBibFlags)<CR>
"
" Commands And Highlightgs:
" {{{
command! -buffer -bang -complete=customlist,atplib#search#SearchHistCompletion -nargs=* S 	:call atplib#search#Search(<q-bang>, <q-args>) | let v:searchforward = ( atplib#search#GetSearchArgs(<q-args>, 'bceswWx')[1] =~# 'x' ? v:searchforward :  ( atplib#search#GetSearchArgs(<q-args>, 'bceswWx')[1] =~# 'b' ? 0 : 1 ) )
nnoremap <buffer> <silent> <Plug>RecursiveSearchn	:exe "S /".@/."/x".(v:searchforward ? "" : "b")<CR>
nnoremap <buffer> <silent> <Plug>RecursiveSearchN	:exe "S /".@/."/x".(v:searchforward ? "b" : "")<CR>

if g:atp_mapNn
" These two maps behaves now like n (N): after forward search n (N) acts as forward (backward), after
" backward search n acts as backward (forward, respectively).

    nnoremap <buffer> <silent> n		<Plug>RecursiveSearchn
    nnoremap <buffer> <silent> N		<Plug>RecursiveSearchN

    " Note: the final step if the mapps n and N are made is in atplib#search#LoadHistory 
endif

command! -buffer -bang 		LocalCommands					:call LocalCommands(1, "", <q-bang>)
command! -buffer -bang -nargs=* -complete=customlist,DsearchComp Dsearch	:call atplib#search#Dsearch(<q-bang>, <q-args>)
command! -buffer -nargs=? -complete=customlist,atplib#OnOffComp ToggleNn	:call atplib#search#ATP_ToggleNn(0,<f-args>)
command! -buffer -bang -nargs=* BibSearch					:call atplib#search#BibSearch(<q-bang>, <q-args>)

" Search map:
command! -buffer -bang -nargs=? Map	:call atplib#helpfunctions#MapSearch(<q-bang>,<q-args>, '')
command! -buffer -bang -nargs=? Nmap	:call atplib#helpfunctions#MapSearch(<q-bang>,<q-args>, 'n')
command! -buffer -bang -nargs=? Imap	:call atplib#helpfunctions#MapSearch(<q-bang>,<q-args>, 'i')
command! -buffer -bang -nargs=? Cmap	:call atplib#helpfunctions#MapSearch(<q-bang>,<q-args>, 'c')
command! -buffer -bang -nargs=? Vmap	:call atplib#helpfunctions#MapSearch(<q-bang>,<q-args>, 'v')
command! -buffer -bang -nargs=? Smap	:call atplib#helpfunctions#MapSearch(<q-bang>,<q-args>, 's')
command! -buffer -bang -nargs=? Omap	:call atplib#helpfunctions#MapSearch(<q-bang>,<q-args>, 'o')
command! -buffer -bang -nargs=? Lmap	:call atplib#helpfunctions#MapSearch(<q-bang>,<q-args>, 'l')
" Hilighlting:
hi link BibResultsFileNames 	Title	
hi link BibResultEntry		ModeMsg
hi link BibResultsMatch		WarningMsg
hi link BibResultsGeneral	Normal

hi link Chapter 		Normal	
hi link Section			Normal
hi link Subsection		Normal
hi link Subsubsection		Normal
hi link CurrentSection		WarningMsg
"}}}
" vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1
ftplugin/ATP_files/tex-fold.vim	[[[1
73
" Language:	latex, tex
" Author:	Johannes Zellner <johannes [at] zellner [dot] org>
" Modified By:  Marcin Szamotulski <mszamot [at] gmail [dot] com>

if exists("g:atp_folding") && !g:atp_folding
    finish
endif

" [-- local settings --]
setlocal foldexpr=TexFold(v:lnum)

" [-- avoid multiple sourcing --]
if exists("*TexFold")
    setlocal foldmethod=expr
    finish
endif

" [-- ATP options --]
if !exists("g:atp_fold_environments")
    let g:atp_fold_environments = 0
endif

let s:class = atplib#search#DocumentClass(b:atp_MainFile)
fun! TexFoldContextWithDepth(line)
    if s:class =~ '^\(ams\)\=art\(icle\)\=$'
	if a:line =~ '\\section\>'		| return 1
	elseif a:line =~ '\\subsection\>'	| return 2
	elseif a:line =~ '\\subsubsection\>'	| return 3
	elseif a:line =~ '\\paragraph\>'	| return 4
	elseif a:line =~ '\\subparagraph\>'	| return 5
	else					| return 0
	endif
    else
	if a:line =~ '\\part\>'			| return 1
	elseif a:line =~ '\\chapter\>'		| return 2
	elseif a:line =~ '\\section\>'		| return 3
	elseif a:line =~ '\\subsection\>'	| return 4
	elseif a:line =~ '\\subsubsection\>'	| return 5
	elseif a:line =~ '\\paragraph\>'	| return 6
	elseif a:line =~ '\\subparagraph\>'	| return 7
	else					| return 0
	endif
    endif
endfun

fun! TexFoldContextFlat(line)
    if a:line =~ '\\\(part\|chapter\|\(sub\)\+section\|\(sub\)\=paragraph\)\>'
	return 1
    else
	return 0
    endif
endfun

fun! TexFold(lnum)
    " remove comments
    let line = substitute(getline(a:lnum), '\(^%\|\s*[^\\]%\).*$', '', 'g')
    " let level = TexFoldContextFlat(line)
      let level = TexFoldContextWithDepth(line)
    if level
	exe 'return ">'.level.'"'
    elseif line =~ '.*\\begin\>.*' && g:atp_fold_environments
	return 'a1'
    elseif line =~ '.*\\end\>.*' && g:atp_fold_environments
	return 's1'
    else
	return '='
    endif
endfun

" [-- trigger indention --]
setlocal foldmethod=expr

" vim:ts=8
ftplugin/ATP_files/url_query.py	[[[1
28
#!/usr/bin/python
# -*- coding: utf-8 -*-
''' Simple url downloader for ATP'''
import sys
if sys.version_info < (3, 0):
    # Python 2.7 code:
    import sys, urllib2, tempfile

    url  = sys.argv[1]
    tmpf = sys.argv[2]

    try:
        f    = open(tmpf, "w")
    except IOError as e:
        print(str(e))
    else:
        data = urllib2.urlopen(url)
        f.write(data.read())
    finally:
        f.close()
else:
    # Python3 code:
    import urllib.request, urllib.error, urllib.parse

    url  = sys.argv[1]
    tmpf = sys.argv[2]

    data = urllib.request.urlretrieve(url,tmpf)
ftplugin/ATP_files/various.vim	[[[1
461
" Author:      Marcin Szamotulski	
" Descriptiion:	These are various editting tools used in ATP.
" Note:	       This file is a part of Automatic Tex Plugin for Vim.
" Language:    tex
" Last Change: Thu Apr 26, 2012 at 19:09:01  +0100

let s:sourced 	= exists("s:sourced") ? 1 : 0
"{{{ ATP_strlen()
" This function is used to measure lenght of a string using :Align, :TexAlign
" commads. See help file of AlignPlugin for g:Align_xstrlen variable.
function! ATP_strlen(x)
    if v:version < 703 || !&conceallevel 
	return strlen(substitute(a:x, '.\Z', 'x', 'g'))
    endif
    let x=a:x
    let hide = ( &conceallevel < 3 ? ' ' : '' )
    " The hide character has to be a non-word character, otherwise for
    " example: \otimes\bigcap -> \otimesx and '\\otimes\>' will not match.
    let greek=[ 
	    \ '\\alpha', '\\beta', '\\gamma', '\\delta', '\\epsilon', '\\varepsilon',
	    \ '\\zeta', '\\eta', '\\theta', '\\vartheta', '\\kappa', '\\lambda', '\\mu',
	    \ '\\nu', '\\xi', '\\pi', '\\varpi', '\\rho', '\\varrho', '\\sigma',
	    \ '\\varsigma', '\\tau', '\\upsilon', '\\phi', '\\varphi', '\\chi', '\\psi', '\\omega',
	    \ '\\Gamma', '\\Delta', '\\Theta', '\\Lambda', '\\Xi', '\\Pi', '\\Sigma',
	    \ '\\Upsilon', '\\Phi', '\\Psi', '\\Omega']
    if &enc == 'utf-8' && g:tex_conceal =~# 'g'
	for gletter in greek
	    let x = substitute(x, gletter, hide, 'g')
	endfor
    endif
"     let g:x_1 = x
    let s:texMathList=[
        \ '|', 'angle', 'approx', 'ast', 'asymp', 'backepsilon', 'backsimeq', 'barwedge', 'because',
        \ 'between', 'bigcap', 'bigcup', 'bigodot', 'bigoplus', 'bigotimes', 'bigsqcup', 'bigtriangledown', 'bigvee',
        \ 'bigwedge', 'blacksquare', 'bot', 'boxdot', 'boxminus', 'boxplus', 'boxtimes', 'bumpeq', 'Bumpeq',
        \ 'cap', 'Cap', 'cdots', 'cdot', 'circ', 'circeq', 'circlearrowleft', 'circlearrowright', 'circledast',
        \ 'circledcirc', 'complement', 'cong', 'coprod', 'cup', 'Cup', 'curlyeqprec', 'curlyeqsucc', 'curlyvee',
        \ 'curlywedge', 'dashv', 'diamond', 'div', 'doteqdot', 'doteq', 'dotplus', 'dotsb', 'dotsc',
        \ 'dotsi', 'dotso', 'dots', 'doublebarwedge', 'downarrow', 'Downarrow', 'emptyset', 'eqcirc', 'eqsim',
        \ 'eqslantgtr', 'eqslantless', 'equiv', 'exists', 'fallingdotseq', 'forall', 'ge', 'geq', 'geqq',
        \ 'gets', 'gneqq', 'gtrdot', 'gtreqless', 'gtrless', 'gtrsim', 'hookleftarrow', 'hookrightarrow', 'iiint',
        \ 'iint', 'Im', 'in', 'infty', 'int', 'lceil', 'ldots', 'leftarrow', 'left\\{',
        \ 'Leftarrow', 'leftarrowtail', 'Leftrightarrow', 
	\ 'leftrightsquigarrow', 'leftthreetimes', 'leqq', 
        \ 'leq', 'lessdot', 'lesseqgtr', 'lesssim', 'le', 'lfloor', 'lmoustache', 'lneqq', 'ltimes', 'mapsto',
        \ 'measuredangle', 'mid', 'mp', 'nabla', 'ncong', 'nearrow', 'neg', 'neq',
        \ 'nexists', 'ne', 'ngeqq', 'ngeq', 'ngtr', 'ni', 'nleftarrow', 'nLeftarrow', 'nLeftrightarrow', 'nleqq',
        \ 'nleq', 'nless', 'nmid', 'notin', 'nprec', 'nrightarrow', 'nRightarrow', 'nsim', 'nsucc',
        \ 'ntriangleleft', 'ntrianglelefteq', 'ntrianglerighteq', 'ntriangleright', 'nvdash', 'nvDash', 'nVdash', 'nwarrow', 'odot',
        \ 'oint', 'ominus', 'oplus', 'oslash', 'otimes', 'owns', 'partial', 'perp', 'pitchfork',
        \ 'pm', 'precapprox', 'preccurlyeq', 'preceq', 'precnapprox', 'precneqq', 'precsim', 'prec', 'prod',
        \ 'propto', 'rceil', 'Re', 'rfloor', 'Rightarrow', 'rightarrowtail', 'rightarrow', 'right\\}',
        \ 'subseteqq', 'subseteq', 'subsetneqq', 'subsetneq', 'subset', 'Subset', 'succapprox', 'succcurlyeq',
        \ 'succeqq', 'succnapprox', 'succneq', 'succsim', 'succ', 'sum', 'Supset', 'supseteqq', 'supseteq', 'supsetneqq',
        \ 'supsetneq', 'surd', 'swarrow', 'therefore', 'times', 'top', 'to', 'trianglelefteq', 'triangleleft',
        \ 'triangleq', 'triangleright', 'trianglerighteq', 'twoheadleftarrow', 'twoheadrightarrow', 'uparrow', 'Uparrow', 'updownarrow', 'Updownarrow',
        \ 'varnothing', 'vartriangle', 'vdash', 'vDash', 'Vdash', 'vdots', 'veebar', 'vee', 'Vvdash',
        \ 'wedge', 'wr', 'gg', 'll', 'backslash', 'langle', 'lbrace', 'lgroup', 'rangle', 'rbrace',
	\ ]
  let s:texMathDelimList=[
     \ '<', '>', '(', ')', '\[', ']', '\\{', 
     \ '\\}', '|', '\\|', '\\backslash', '\\downarrow', '\\Downarrow', '\\langle', '\\lbrace', 
     \ '\\lceil', '\\lfloor', '\\lgroup', '\\lmoustache', '\\rangle', '\\rbrace', '\\rceil', 
     \ '\\rfloor', '\\rgroup', '\\rmoustache', '\\uparrow', '\\Uparrow', '\\updownarrow', '\\Updownarrow']
    if g:tex_conceal =~# 'm'
	for symb in s:texMathList
	    let x=substitute(x, '\C\\'.symb.'\>', hide, 'g')
	    " The pattern must end with '\>', since there are commands with
	    " the same begining, for example \le and \left, etc...
	endfor
	for symb in s:texMathDelimList
	    let x=substitute(x, '\\[Bb]igg\=[lr]\>'.symb, hide, 'g') 
	endfor
	let x=substitute(x, '\\\%(left\|right\)\>', '', 'g')
    endif
"     let g:x_2 = x
    if &enc == 'utf-8' && g:tex_conceal =~# 's'
	let x=substitute(x, '\\\@<![_^]\%({.\)\=', '', 'g')
    endif
"     let g:x_3 = x
    if &enc == 'utf-8' && g:tex_conceal =~# 'a'
	for accent in [
		    \ '\\[`''\^"~kruv]{\=[aA]}\=\>',
		    \ '\\[`''\^"~kruv]{\=[aA]}\=\>',
		    \ '\\[`\^.cv]{\=[cC]}\=\>',
		    \ '\\[v]{\=[dD]}\=\>',
		    \ '\\[`''\^"~.ckuv]{\=[eE]}\=\>',
		    \ '\\[`.cu]{\=[gG]}\=\>',
		    \ '\\[`''\^"~.u]{\=[iI]}\=\>',
		    \ '\\[''\^"cv]{\=[lL]}\=\>',
		    \ '\\[''~cv]{\=[nN]}\=\>',
		    \ '\\[`''\^"~.Hku]{\=[oO]}\=\>',
		    \ '\\[''cv]{\=[rR]}\=\>',
		    \ '\\[''\^cv]{\=[sS]}\=\>',
		    \ '\\[''cv]{\=[tT]}\=\>',
		    \ '\\[`''\^"~Hru]{\=[uU]}\=\>',
		    \ '\\[\^]{\=[wW]}\=\>',
		    \ '\\[`''\^"~]{\=[yY]}\=\>',
		    \ '\\[''.v]{\=[zZ]}\=\>',
		    \ '\\[`''\^"~.cHkruv]{\=[aA]}\=\>',
		    \ '\\[`''\^"~.u]{\=\\i}\=\>',
		    \ '\\AA\>', '\\[oO]\>', '\\AE\>', '\\ae\>', '\\OE\>', '\\ss\>' ]
	    let x=substitute(x, accent, hide, 'g')
	endfor
    endif
    " Add custom concealed symbols.
"     let g:x_4 = x
    let x=substitute(x,'.','x','g')
"     let g:x=x
    return strlen(x)
endfunction
"}}}
" {{{ InsertItem()
" ToDo: indent
function! InsertItem()
    let begin_line	= searchpair( '\\begin\s*{\s*\%(enumerate\|itemize\|thebibliography\)\s*}', '', '\\end\s*{\s*\%(enumerate\|itemize\|thebibliography\)\s*}', 'bnW')
    let saved_pos	= getpos(".")
    call cursor(line("."), 1)

    if g:atp_debugInsertItem
	let g:debugInsertItem_redir= "redir! > ".g:atp_TempDir."/InsertItem.log"
	exe "redir! > ".g:atp_TempDir."/InsertItem.log"
    endif

    if getline(begin_line) =~ '\\begin\s*{\s*thebibliography\s*}'
	call cursor(saved_pos[1], saved_pos[2])
	let col = ( col(".") == 1 ? 0 : col("."))
	let new_line	= strpart(getline("."), 0, col) . '\bibitem' . strpart(getline("."), col)
	call setline(line("."), new_line)

	" Indent the line:
	if &l:indentexpr != ""
	    let v:lnum=saved_pos[1]
	    execute "let indent = " . &l:indentexpr
	    let i 	= 1
	    let ind 	= ""
	    while i <= indent
		let ind	.= " "
		let i	+= 1
	    endwhile
	else
	    indent	= -1
	    ind 	=  matchstr(getline("."), '^\s*')
	endif
	let indent_old = len(matchstr(getline("."), '^\s*'))
	call setline(line("."), ind . substitute(getline("."), '^\s*', '', ''))
	let a=(saved_pos[2]==1 ? -1 : 0 )
	let saved_pos[2]	+= len('\bibitem') + indent - indent_old + a
	call cursor(saved_pos[1], saved_pos[2])

	if g:atp_debugInsertItem
	    let g:InsertIntem_return = 0
	    silent echo "0] return"
	    redir END
	endif
	return
    endif

    " This will work with \item [[1]], but not with \item [1]]
    let [ bline, bcol]	= searchpos('\\item\s*\zs\[', 'b', begin_line) 
    if bline == 0
	call cursor(saved_pos[1], saved_pos[2])
	let col= (col(".") == 1 ? 0 : col("."))
	if search('\\item\>', 'nb', begin_line)
	    let new_line	= strpart(getline("."), 0, col) . '\item '. strpart(getline("."), col)
	else
	    let new_line	= strpart(getline("."), 0, col) . '\item'. strpart(getline("."), col)
	endif
	call setline(line("."), new_line)

	" Indent the line:
	if &l:indentexpr != ""
	    let v:lnum=saved_pos[1]
	    execute "let indent = " . &l:indentexpr
	    let i 	= 1
	    let ind 	= repeat(" ", indent)
	else
	    let indent	= -1
	    let ind 	=  matchstr(getline("."), '^\s*')
	endif
	if g:atp_debugInsertItem
	    silent echo "1] indent=".len(ind)
	endif
	call setline(line("."), ind . substitute(getline("."), '^\s*', '', ''))

	" Set the cursor position
	let saved_pos[2]	+= len('\item') + indent
	keepjumps call setpos(".", saved_pos)

	if g:atp_debugInsertItem
	    let g:debugInsertItem_return = 1
	    silent echo "1] return"
	    redir END
	endif
	return ""
    endif
    let [ eline, ecol]	= searchpairpos('\[', '', '\]', 'nr', '', line("."))
    if eline != bline
	if g:atp_debugInsertItem
	    let g:debugInsertItem_return = 2
	    silent echo "2] return"
	    redir END
	endif
	return ""
    endif

    let item		= strpart(getline("."), bcol, ecol - bcol - 1)
    let bpat		= '(\|{\|\['
    let epat		= ')\|}\|\]\|\.'
    let number		= matchstr(item, '\d\+')
    let subNr		= matchstr(item, '\d\+\zs\a\ze')
    let space		= matchstr(getline("."), '\\item\zs\s*\ze\[')
    if nr2char(number) != "" && subNr == "" 
	let new_item	= substitute(item, number, number + 1, '')
	if g:atp_debugInsertItem
	    silent echo "(1) new_item=".new_item
	endif
    elseif item =~ '\%('.bpat.'\)\=\s*\%(i\|ii\|iii\|iv\|v\|vi\|vii\|viii\|ix\)\%('.epat.'\)\=$'
	let numbers	= [ 'i', 'ii', 'iii', 'iv', 'v', 'vi', 'vii', 'viii', 'ix', 'x' ]
	let roman	= matchstr(item, '\%('.bpat.'\)\=\s*\zs\w\+\ze\s*\%('.epat.'\)\=$')
	let new_roman	= get(numbers, index(numbers, roman) + 1, 'xi') 
	let new_item	= substitute(item,  '^\%('.bpat.'\)\=\s*\zs\a\+\ze\s*\%('.epat.'\)\=$', new_roman, 'g') 
	if g:atp_debugInsertItem
	    silent echo "(2) new_item=".new_item
	endif
    elseif nr2char(number) != "" && subNr != ""
	let alphabet 	= [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'w', 'x', 'y', 'z' ] 
	let char	= matchstr(item, '^\%('.bpat.'\)\=\s*\d\+\zs\a\ze\s*\%('.epat.'\)\=$')
	let new_char	= get(alphabet, index(alphabet, char) + 1, 'z')
	let new_item	= substitute(item, '^\%('.bpat.'\)\=\s*\d\+\zs\a\ze\s*\%('.epat.'\)\=$', new_char, 'g')
	if g:atp_debugInsertItem
	    silent echo "(3) new_item=".new_item
	endif
    elseif item =~ '\%('.bpat.'\)\=\s*\w\s*\%('.epat.'\)\='
	let alphabet 	= [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'w', 'x', 'y', 'z' ] 
	let char	= matchstr(item, '^\%('.bpat.'\)\=\s*\zs\w\ze\s*\%('.epat.'\)\=$')
	let new_char	= get(alphabet, index(alphabet, char) + 1, 'a')
	let new_item	= substitute(item, '^\%('.bpat.'\)\=\s*\zs\w\ze\s*\%('.epat.'\)\=$', new_char, 'g')
	if g:atp_debugInsertItem
	    silent echo "(4) new_item=".new_item
	endif
    else
	let new_item	= item
	if g:atp_debugInsertItem
	    silent echo "(5) new_item=".item
	endif
    endif

    keepjumps call setpos(".", saved_pos)

    let col = (col(".")==1 ? 0 : col("."))
    let new_line	= strpart(getline("."), 0, col) . '\item' . space . '[' . new_item . '] ' . strpart(getline("."), col)
    if g:atp_debugInsertItem
	silent echo "new_line=".new_line
    endif
    call setline(line("."), new_line)

    " Indent the line:
    if &l:indentexpr != ""
	let v:lnum=saved_pos[1]
	execute "let indent = " . &l:indentexpr
	let i 	= 1
	let ind 	= ""
	while i <= indent
	    let ind	.= " "
	    let i	+= 1
	endwhile
    else
	ind 	= matchstr(getline("."), '^\s*')
    endif
    if g:atp_debugInsertItem
	silent echo "indent=".len(ind)
    endif
    let indent_old = len(matchstr(getline("."), '^\s*'))
    call setline(line("."), ind . substitute(getline("."), '^\s*', '', ''))

    " Set the cursor position
    let saved_pos[2]	+= len('\item' . space . '[' . new_item . ']') + indent - indent_old
    keepjumps call setpos(".", saved_pos)


    if g:atp_debugInsertItem
	let g:debugInsertItem_return = 3
	silent echo "3] return"
	redir END
    endif
    return ""
endfunction
" }}}
" InsertEnvironment() {{{ 
function! <SID>InsertEnvironment(bang,env_name)
    if a:bang == ""
	if getline(".") =~ '^\s*$'
	    delete _
	endif
	call append(line("."), ['\begin{'.a:env_name.'}', '\end{'.a:env_name.'}']) 
	normal! j$
    else
	let line=getline(".")[:col(".")-1]."\\begin{".a:env_name."}\\end{".a:env_name."}".getline(".")[col("."):]
	call setline(line("."), line)
	call search('\\end', '', line("."))
    endif
endfunction "}}}
"{{{ Variables
if !exists("g:atp_no_toggle_environments")
    let g:atp_no_toggle_environments=[ 'document', 'tikzpicture', 'picture']
endif
if !exists("g:atp_toggle_environment_1")
    let g:atp_toggle_environment_1=[ 'center', 'flushleft', 'flushright', 'minipage' ]
endif
if !exists("g:atp_toggle_environment_2")
    let g:atp_toggle_environment_2=[ 'enumerate', 'itemize', 'list', 'description' ]
endif
if !exists("g:atp_toggle_environment_3")
    let g:atp_toggle_environment_3=[ 'quotation', 'quote', 'verse' ]
endif
if !exists("g:atp_toggle_environment_4")
    let g:atp_toggle_environment_4=[ 'theorem', 'proposition', 'lemma' ]
endif
if !exists("g:atp_toggle_environment_5")
    let g:atp_toggle_environment_5=[ 'corollary', 'remark', 'note' ]
endif
if !exists("g:atp_toggle_environment_6")
    let g:atp_toggle_environment_6=[  'equation', 'align', 'array', 'alignat', 'gather', 'flalign', 'multline'  ]
endif
if !exists("g:atp_toggle_environment_7")
    let g:atp_toggle_environment_7=[ 'smallmatrix', 'pmatrix', 'bmatrix', 'Bmatrix', 'vmatrix' ]
endif
if !exists("g:atp_toggle_environment_8")
    let g:atp_toggle_environment_8=[ 'tabbing', 'tabular']
endif
if !exists("g:atp_toggle_labels")
    let g:atp_toggle_labels=1
endif
"}}}
" ToDo notes
" {{{ ToDo
"
" TODO if the file was not found ask to make one.
function! ToDo(keyword, stop, bang, ...)

    if a:0 == 0
	let bufname	= bufname("%")
    else
	let bufname	= a:1
    endif

    let b_pat	= ( a:bang == "!" ? '' : '^\s*' )

    " read the buffer
    let texfile	= getbufline(bufname, 1, "$")

    " find ToDos
    let todo = {}
    let nr=1
    for line in texfile
	if line =~ b_pat.'%\s*' . a:keyword 
	    call extend(todo, { nr : line }) 
	endif
	let nr += 1
    endfor

    " Show ToDos
    echohl atp_Todo
    if len(keys(todo)) == 0
	echomsg "[ATP:] list for ".b_pat."'%\s*" . a:keyword . "' in '" . bufname . "' is empty."
	return
    endif
    echomsg "[ATP:] list for ".b_pat."'%\s*" . a:keyword . "' in '" . bufname . "':"
    let sortedkeys=sort(keys(todo), "atplib#CompareNumbers")
    for key in sortedkeys
	" echo the todo line.
	echo key . " " . substitute(substitute(todo[key],'%','',''),'\t',' ','g')
	let true	= 1
	let a		= 1
	let linenr	= key
	" show all comment lines right below the found todo line.
	while true && texfile[linenr] !~ b_pat.'%\s*\c\<todo\>' 
	    let linenr=key+a-1
	    if texfile[linenr] =~ b_pat.'\s*%' && texfile[linenr] !~ a:stop
		" make space of length equal to len(linenr)
		let space=""
		let j=0
		while j < len(linenr)
		    let space=space . " " 
		    let j+=1
		endwhile
		echo space . " " . substitute(substitute(texfile[linenr],'%','',''),'\t',' ','g')
	    else
		let true = 0
	    endif
	    let a += 1
	endwhile
    endfor
    echohl None
endfunction
" }}}

" COMMANDS AND MAPS:
" Maps: "{{{1
nmap 	<buffer> <silent>	<Plug>Unwrap		:call atplib#various#Unwrap()<CR>
nmap 	<buffer> <silent> 	<Plug>Dictionary	:call atplib#various#Dictionary(expand("<cword>"))<CR>
map 	<buffer> 		<Plug>CommentLines	:call atplib#various#Comment(1)<CR>
map 	<buffer> 		<Plug>UnCommentLines 	:call atplib#various#Comment(0)<CR>
vmap 	<buffer> 		<Plug>WrapSelection	:<C-U>call atplib#various#WrapSelection('')<CR>i
vmap	<buffer> <silent> 	<Plug>WrapEnvironment	:<C-U>call atplib#various#WrapEnvironment('', 1)<CR>
vmap 	<buffer> 	<Plug>InteligentWrapSelection	:<C-U>call atplib#various#InteligentWrapSelection('')<CR>i
nmap 				<Plug>TexAlign		:call atplib#various#TexAlign(( g:atp_TexAlign_join_lines ? "!" : "" ))<CR>
nnoremap 			<Plug>Replace		:call atplib#various#Replace()<CR>
nnoremap <silent> <buffer> 	<Plug>ToggleStar	:call atplib#various#ToggleStar()<CR>
nnoremap <silent> <buffer> 	<Plug>ToggleEnvForward	:call atplib#various#ToggleEnvironment(0, 1)<CR>
nnoremap <silent> <buffer> 	<Plug>ToggleEnvBackward	:call atplib#various#ToggleEnvironment(0, -1)<CR>
nnoremap <silent> <buffer> 	<Plug>ChangeEnv		:call atplib#various#ToggleEnvironment(1)<CR>
nnoremap <silent> <buffer> 	<Plug>TexDoc		:TexDoc 
" Commands: "{{{1
command! -nargs=1 -bang -complete=customlist,atplib#various#EnvCompletion InsertEnv :call <SID>InsertEnvironment(<q-bang>,<q-args>)
command! -nargs=? -bang -complete=file  Open call atplib#tools#Open(<q-bang>, g:atp_LibraryPath, g:atp_OpenTypeDict, <q-args>)
command! -buffer Unwrap	:call atplib#various#Unwrap()
command! -buffer -nargs=1 -complete=custom,atplib#various#Complete_Dictionary Dictionary :call atplib#various#Dictionary(<f-args>)
command! -buffer -nargs=* SetUpdateTime				:call atplib#various#UpdateTime(<f-args>)
command! -buffer -nargs=* -complete=file Wdiff			:call atplib#various#Wdiff(<f-args>)
command! -buffer -nargs=* -complete=custom,atplib#various#WrapSelection_compl -range Wrap			:call atplib#various#WrapSelection(<f-args>)
command! -buffer -nargs=? -complete=customlist,atplib#various#EnvCompletion -range WrapEnvironment		:call atplib#various#WrapEnvironment(<f-args>)
command! -buffer -nargs=? -range IWrap				:call atplib#various#InteligentWrapSelection(<args>)
command! -buffer -bang	TexAlign				:call atplib#various#TexAlign(<q-bang>)
command! -buffer 	ToggleStar   				:call atplib#various#ToggleStar()<CR>
command! -buffer -nargs=? ToggleEnv	   			:call atplib#various#ToggleEnvironment(0, <f-args>)
command! -buffer -nargs=* -complete=customlist,atplib#various#EnvCompletion ChangeEnv				:call atplib#various#ToggleEnvironment(1, <f-args>)
command! -buffer -nargs=1 ChangeLabel				:call atplib#various#ChangeLabel(<q-args>)
command! -buffer -nargs=* -complete=customlist,atplib#various#TeXdoc_complete TexDoc 	:call atplib#various#TexDoc(<f-args>)
command! -buffer -bang 	Delete					:call atplib#various#Delete(<q-bang>)
nmap <silent> <buffer>	 <Plug>Delete				:call atplib#various#Delete("")<CR>
command! -buffer 	OpenLog					:call atplib#various#OpenLog()
nnoremap <silent> <buffer> <Plug>OpenLog			:call atplib#various#OpenLog()<CR>
command! -buffer 	TexLog					:call atplib#various#TexLog()
nnoremap <silent> <buffer> <Plug>TexLog				:call atplib#various#TexLog()<CR>
command! -buffer 	PdfFonts				:call atplib#various#PdfFonts()
nnoremap <silent> <buffer> <Plug>PdfFonts			:call atplib#various#PdfFonts()<CR>
command! -complete=custom,atplib#various#Complete_lpr  -buffer -nargs=* SshPrint 	:call atplib#various#SshPrint("", <f-args>)
command! -complete=custom,atplib#various#CompleteLocal_lpr  -buffer -nargs=* Lpr	:call atplib#various#Lpr(<f-args>)
nnoremap <buffer> 	<Plug>SshPrint				:SshPrint 
command! -buffer 	Lpstat					:call atplib#various#Lpstat()
nnoremap <silent> <buffer> <Plug>Lpstat				:call atplib#various#Lpstat()<CR>
command! -buffer 	ListPrinters				:echo atplib#various#ListPrinters("", "", "")
" List Packages:
command! -buffer 	ShowPackages				:let b:atp_PackageList = atplib#search#GrepPackageList() | echo join(b:atp_PackageList, "\n")
if &l:cpoptions =~# 'B'
    command! -buffer -nargs=? -complete=buffer -bang ToDo	:call ToDo('\c\<to\s*do\s*\>','\s*%\s*$\|\s*%\c.*\<note\>',<q-bang>, <f-args>)
    command! -buffer -nargs=? -complete=buffer -bang Note	:call ToDo('\c\<note\s*\>','\s*%\s*$\|\s*%\c.*\<to\s*do\>', <q-bang>, <f-args>)
else
    command! -buffer -nargs=? -complete=buffer ToDo		:call ToDo('\\c\\<to\\s*do>','\\s*%\\s*$\\|\\s*%\\c.*\\<note\\>',<f-args>)
    command! -buffer -nargs=? -complete=buffer Note		:call ToDo('\\c\\<note\\>','\\s*%\\s*$\\|\\s*%\\c.*\\<to\\s*do\\>',<f-args>)
endif
command! -buffer ReloadATP					:call atplib#various#ReloadATP("!")
command! -bang -buffer -nargs=1 AMSRef				:call atplib#various#AMSRef(<q-bang>, <q-args>)
command! -buffer	Preamble				:call atplib#various#Preamble()
command! -range  -bang	WordCount				:call atplib#various#ShowWordCount(<q-bang>,[<q-line1>,<q-line2>])
if has("unix") && g:atp_atpdev
    command! -nargs=? -complete=custom,atplib#various#DebugPrintComp DebugPrint	:call atplib#various#DebugPrint(<q-args>)
endif 
" vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1
ftplugin/ATP_files/vimcomplete.bst	[[[1
306
ENTRY
  { address author booktitle chapter doi edition editor eid howpublished institution isbn issn journal key month note number organization pages publisher school series title type volume year }
  {}
  { label }
STRINGS { s t}

FUNCTION {output}
{ 's :=
  %purify$
  %"}{" * write$
  "||" * write$
  s
}
FUNCTION {fin.entry}
%{ "}" * write$
{ write$
  newline$
}

FUNCTION {not}
{   { #0 }
    { #1 }
  if$
}
FUNCTION {and}
{   'skip$
    { pop$ #0 }
  if$
}
FUNCTION {or}
{   { pop$ #1 }
    'skip$
  if$
}
FUNCTION {field.or.null}
{ duplicate$ empty$
    { pop$ "" }
    'skip$
  if$
}

FUNCTION {capitalize}
{ "u" change.case$ "t" change.case$ }

FUNCTION {space.word}
{ " " swap$ * " " * }

FUNCTION {bbl.and}      { "&"}
FUNCTION {bbl.etal}     { "et al." }

INTEGERS { nameptr namesleft numnames }

STRINGS  { bibinfo}

FUNCTION {format.names}
{ duplicate$ empty$ 'skip$ {
  's :=
  "" 't :=
  #1 'nameptr :=
  s num.names$ 'numnames :=
  numnames 'namesleft :=
    { namesleft #0 > }
    { s nameptr
      %"{vv~}{ll}{, f.}{, jj}"
      "{vv }{ll}{}{}"
      format.name$
      't :=
      nameptr #1 >
        {
          namesleft #1 >
            { ", " * t * }
            {
              s nameptr "{ll}" format.name$ duplicate$ "others" =
                { 't := }
                { pop$ }
              if$
              t "others" =
                {
                  " " * bbl.etal *
                }
                {
                  bbl.and
                  space.word * t *
                }
              if$
            }
          if$
        }
        't
      if$
      nameptr #1 + 'nameptr :=
      namesleft #1 - 'namesleft :=
    }
  while$
  } if$
}

FUNCTION {format.authors}
{ author empty$
    {editor format.names} {author format.names}
  if$
}

FUNCTION {format.title}
{ title
  duplicate$ empty$ 'skip$
    { "t" change.case$ }
  if$
}
FUNCTION {output.label}
{ newline$
  %"{" cite$ * write$
  cite$ write$
  ""
}


FUNCTION {format.date}
{
  ""
  duplicate$ empty$
  year  duplicate$ empty$
    { swap$ 'skip$
        { "there's a month but no year in " cite$ * warning$ }
      if$
      *
    }
    { swap$ 'skip$
        {
          swap$
          " " * swap$
        }
      if$
      *
    }
  if$
}

FUNCTION {output.entry}
{ 's :=
  output.label
  s output
  format.authors output
  format.date output
  format.title output
  fin.entry
}

FUNCTION {default.type}     {"?" output.entry}

FUNCTION {article}          {"a" output.entry}
FUNCTION {book}             {"B" output.entry}
FUNCTION {booklet}          {"k" output.entry}
FUNCTION {conference}       {"f" output.entry}
FUNCTION {inbook}           {"b" output.entry}
FUNCTION {incollection}     {"c" output.entry}
FUNCTION {inproceedings}    {"p" output.entry}
FUNCTION {manual}           {"m" output.entry}
FUNCTION {mastersthesis}    {"Master" output.entry}
FUNCTION {misc}             {"-" output.entry}
FUNCTION {phdthesis}        {"PhD" output.entry}
FUNCTION {proceedings}      {"P" output.entry}
FUNCTION {techreport}       {"r" output.entry}
FUNCTION {unpublished}      {"u" output.entry}


READ
FUNCTION {sortify}
{ purify$
  "l" change.case$
}
INTEGERS { len }
FUNCTION {chop.word}
{ 's :=
  'len :=
  s #1 len substring$ =
    { s len #1 + global.max$ substring$ }
    's
  if$
}
FUNCTION {sort.format.names}
{ 's :=
  #1 'nameptr :=
  ""
  s num.names$ 'numnames :=
  numnames 'namesleft :=
    { namesleft #0 > }
    { s nameptr
      "{vv{ } }{ll{ }}{  f{ }}{  jj{ }}"
      format.name$ 't :=
      nameptr #1 >
        {
          "   "  *
          namesleft #1 = t "others" = and
            { "zzzzz" * }
            { t sortify * }
          if$
        }
        { t sortify * }
      if$
      nameptr #1 + 'nameptr :=
      namesleft #1 - 'namesleft :=
    }
  while$
}

FUNCTION {sort.format.title}
{ 't :=
  "A " #2
    "An " #3
      "The " #4 t chop.word
    chop.word
  chop.word
  sortify
  #1 global.max$ substring$
}
FUNCTION {author.sort}
{ author empty$
    { key empty$
        { "to sort, need author or key in " cite$ * warning$
          ""
        }
        { key sortify }
      if$
    }
    { author sort.format.names }
  if$
}
FUNCTION {author.editor.sort}
{ author empty$
    { editor empty$
        { key empty$
            { "to sort, need author, editor, or key in " cite$ * warning$
              ""
            }
            { key sortify }
          if$
        }
        { editor sort.format.names }
      if$
    }
    { author sort.format.names }
  if$
}
FUNCTION {author.organization.sort}
{ author empty$
    { organization empty$
        { key empty$
            { "to sort, need author, organization, or key in " cite$ * warning$
              ""
            }
            { key sortify }
          if$
        }
        { "The " #4 organization chop.word sortify }
      if$
    }
    { author sort.format.names }
  if$
}
FUNCTION {editor.organization.sort}
{ editor empty$
    { organization empty$
        { key empty$
            { "to sort, need editor, organization, or key in " cite$ * warning$
              ""
            }
            { key sortify }
          if$
        }
        { "The " #4 organization chop.word sortify }
      if$
    }
    { editor sort.format.names }
  if$
}
FUNCTION {presort}
{ type$ "book" =
  type$ "inbook" =
  or
    'author.editor.sort
    { type$ "proceedings" =
        'editor.organization.sort
        { type$ "manual" =
            'author.organization.sort
            'author.sort
          if$
        }
      if$
    }
  if$
  "    "
  *
  year field.or.null sortify
  *
  "    "
  *
  title field.or.null
  sort.format.title
  *
  #1 entry.max$ substring$
  'sort.key$ :=
}
ITERATE {presort}
SORT
ITERATE {call.type$}
ftplugin/bib_atp.vim	[[[1
346
" Title:       Vim filetype plugin file
" Author:      Marcin Szamotulski
" Email:       mszamot [AT] gmail [DOT] com
" Mailing List: atp-vim-list [AT] lists.sourceforge.net
" Language:    bib
" Last Change: Sun Sep 18, 2011 at 11:42  +0100
" Copyright Statement: 
" 	  This file is part of Automatic Tex Plugin for Vim.
"
"     Automatic Tex Plugin for Vim is free software: you can redistribute it
"     and/or modify it under the terms of the GNU General Public License as
"     published by the Free Software Foundation, either version 3 of the
"     License, or (at your option) any later version.
" 
"     Automatic Tex Plugin for Vim is distributed in the hope that it will be
"     useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
"     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
"     General Public License for more details.
" 
"     You should have received a copy of the GNU General Public License along
"     with Automatic Tex Plugin for Vim.  If not, see <http://www.gnu.org/licenses/>.
"
"     This licence applies to all files shipped with Automatic Tex Plugin.

call atplib#ReadATPRC()
if !exists("g:atp_vmap_bracket_leader")
    let g:atp_vmap_bracket_leader = '\'
endif

" Variables:
" {{{ bib fields
if !exists("g:atpbib_pathseparator")
    if has("win16") || has("win32") || has("win64") || has("win95")
	let g:atpbib_pathseparator = "\\"
    else
	let g:atpbib_pathseparator = "/"
    endif 
endif
" if !exists("g:atpbib_WgetOutputFile")
"     let tmpname = tempname()
"     let g:atpbib_WgetOutputFile = tmpname . g:atpbib_pathseparator . "amsref.html"
" endif
" if !exists("g:atpbib_wget")
"     let g:atpbib_wget="wget -O " . g:atpbib_WgetOutputFile
" endif
if !exists("g:atpbib_WgetOutputFile")
    let g:atpbib_WgetOutputFile = "amsref.html"
endif
if !exists("g:atpbib_wget")
    let g:atpbib_wget="wget"
endif
if !exists("g:atpbib_Article")
    let g:atpbib_Article = [ '@article{',
		\ '	Author	= {},',
		\ '	Title	= {},',
		\ '	Journal	= {},',
		\ '	Year	= {},', 
		\ '}' ]
endif
nmap <buffer> <LocalLeader>a	:call append(line("."), g:atpbib_Article)<CR>
if !exists("g:atpbib_Book")
    let g:atpbib_Book = [ '@book{' ,
		\ '	Author     	= {},',
		\ '	Title      	= {},',
		\ '	Publisher  	= {},',
		\ '	Year       	= {},', 
		\ '}' ]
endif
if !exists("g:atpbib_Booklet")
    let g:atpbib_Booklet = [ '@booklet{' ,
		\ '	Title      	= {},', 
		\ '}' ]
endif
if !exists("g:atpbib_Conference")
    let g:atpbib_Conference = [ '@conference{' ,
		\ '	Author     	= {},',
		\ '	Title      	= {},',
		\ '	Booktitle  	= {},',
		\ '	Publisher  	= {},',
		\ '	Year       	= {},',
		\ '}' ]
endif
if !exists("g:atpbib_InBook")
    let g:atpbib_InBook = [ '@inbook{' ,
		\ '	Author     	= {},',
		\ '	Title      	= {},',
		\ '	Chapter    	= {},',
		\ '	Publisher  	= {},',
		\ '	Year       	= {},',
		\ '}' ]
endif
if !exists("g:atpbib_InCollection")
    let g:atpbib_InCollection = [ '@incollection{' ,
		\ '	Author     	= {},',
		\ '	Title      	= {},',
		\ '	Booktitle  	= {},',
		\ '	Publisher  	= {},',
		\ '	Year       	= {},',
		\ '}' ]
endif
if !exists("g:atpbib_InProceedings")
    let g:atpbib_InProceedings = [ '@inproceedings{' ,
		\ '	Author     	= {},',
		\ '	Title      	= {},',
		\ '	Booktitle  	= {},',
		\ '	Publisher  	= {},',
		\ '	Year       	= {},',
		\ '}' ]
endif
if !exists("g:atpbib_Manual")
    let g:atpbib_Manual = [ '@manual{' ,
		\ '	Title      	= {},',
		\ '}' ]
endif
if !exists("g:atpbib_MastersThesis")
    let g:atpbib_MastersThesis = [ '@mastersthesis{' ,
		\ '	Author     	= {},',
		\ '	Title      	= {},',
		\ '	School     	= {},',
		\ '	Year       	= {},',
		\ '}' ]
endif
if !exists("g:atpbib_Misc")
    let g:atpbib_Misc = [ '@misc{',
		\ '	Title      	= {},',
		\ '}' ]
endif
if !exists("g:atpbib_PhDThesis")
    let g:atpbib_PhDThesis = [ '@phdthesis{' ,
		\ '	Author     	= {},',
		\ '	Title      	= {},',
		\ '	School     	= {},',
		\ '	Year       	= {},',
		\ '}' ]
endif
if !exists("g:atpbib_Proceedings")
    let g:atpbib_Proceedings = [ '@proceedings{' ,
		\ '	Title      	= {},',
		\ '	Year       	= {},', 
		\ '}' ]
endif
if !exists("g:atpbib_TechReport")
    let g:atpbib_TechReport = [ '@TechReport{' ,
		\ '	Author     	= {},',
		\ '	Title      	= {},',
		\ '	Institution	= {},',
		\ '	Year       	= {},', 
		\ '}' ]
endif
if !exists("g:atpbib_Unpublished")
    let g:atpbib_Unpublished = [ '@unpublished{',
		\ '	Author     	= {},',
		\ '	Title      	= {},',
		\ '	Note       	= {},',
		\ '}' ]
endif
" }}}

" AMSRef:
" {{{ <SID>AMSRef
try
function! <SID>GetAMSRef(what)
    let what = substitute(a:what, '\s\+', ' ',	'g') 
    let what = substitute(what, '%',	'%25',	'g')
    let what = substitute(what, ',',	'%2C',	'g') 
    let what = substitute(what, ':',	'%3A',	'g')
    let what = substitute(what, ';',	'%3B',	'g')
    let what = substitute(what, '/',	'%2F',	'g')
    let what = substitute(what, '?',	'%3F',	'g')
    let what = substitute(what, '+',	'%2B',	'g')
    let what = substitute(what, '=',	'%3D',	'g')
    let what = substitute(what, '#',	'%23',	'g')
    let what = substitute(what, '\$',	'%24',	'g')
    let what = substitute(what, '&',	'%26',	'g')
    let what = substitute(what, '@',	'%40',	'g')
    let what = substitute(what, ' ',	'+',	'g')


    " Get data from AMS web site.
    let atpbib_WgetOutputFile = tempname()
    let URLquery_path = split(globpath(&rtp, 'ftplugin/ATP_files/url_query.py'), "\n")[0]
    let url="http://www.ams.org/mathscinet-mref?ref=".what."&dataType=bibtex"
    let cmd=g:atp_Python." ".URLquery_path." ".shellescape(url)." ".shellescape(atpbib_WgetOutputFile)
    call system(cmd)
    let loclist = getloclist(0)

    try
	exe '1lvimgrep /\CNo Unique Match Found/j ' . fnameescape(atpbib_WgetOutputFile)
    catch /E480/
    endtry
    if len(getloclist(0))
	echohl WarningMsg
	echomsg "[ATP:] No Unique Match Found"
	echohl None
	return [0]
    endif
    let pattern = '@\%(article\|book\%(let\)\=\|conference\|inbook\|incollection\|\%(in\)\=proceedings\|manual\|masterthesis\|misc\|phdthesis\|techreport\|unpublished\)\s*{\|^\s*\%(ADDRESS\|ANNOTE\|AUTHOR\|BOOKTITLE\|CHAPTER\|CROSSREF\|EDITION\|EDITOR\|HOWPUBLISHED\|INSTITUTION\|JOURNAL\|KEY\|MONTH\|NOTE\|NUMBER\|ORGANIZATION\|PAGES\|PUBLISHER\|SCHOOL\|SERIES\|TITLE\|TYPE\|VOLUME\|YEAR\|MRCLASS\|MRNUMBER\|MRREVIEWER\)\s*=\s*.*$'
    try 
	exe 'lvimgrep /'.pattern.'/j ' . fnameescape(atpbib_WgetOutputFile)
    catch /E480:/
    endtry
    let data = getloclist(0)
    call setloclist(0, loclist)
    if !len(data) 
	echohl WarningMsg
	echomsg "[ATP:] nothing found."
	echohl None
	return [0]
    endif

    let type_pattern= '@\%(article\|book\%(let\)\=\|conference\|inbook\|incollection\|\%(in\)\=proceedings\|manual\|masterthesis\|misc\|phdthesis\|techreport\|unpublished\)\>'
    let bdata		= filter(copy(data), "v:val['text'] =~ type_pattern")
    let blinenumbers	= map(copy(bdata), 'v:val["lnum"]')
    let begin		= max(blinenumbers)
    let linenumbers	= map(copy(data), 'v:val["lnum"]')
    let end		= max(linenumbers)

    let bufnr = bufnr(atpbib_WgetOutputFile)
    " To use getbufline() buffer must be loaded. It is enough to use :buffer
    " command because vimgrep loads buffer and then unloads it. 
    execute "buffer " . bufnr
    let bibdata	= getbufline(bufnr, begin, end)
    execute "bdelete " . bufnr 
    let type = matchstr(bibdata[0], '@\%(article\|book\%(let\)\=\|conference\|inbook\|incollection\|\%(in\)\=proceedings\|manual\|masterthesis\|misc\|phdthesis\|techreport\|unpublished\)\ze\s*\%("\|{\|(\)')
"     Suggest Key:
    let bibkey = input("Provide a key (Enter for the AMS bibkey): ")
    if !empty(bibkey)
	let bibdata[0] = type . '{' . bibkey . ','
    else
	let bibdata[0] = substitute(matchstr(bibdata[0], '@\w*.*$'), '\(@\w*\)\(\s*\)', '\1', '')
    endif
    call add(bibdata, "}")

    "Go to begin of next entry or end of last entry
    let line = NEntry('nW')
    if line == line(".")
	call EntryEnd("")
    else
	call cursor(line(".")-1,1)
    endif

    "Append the bibdata:
    if getline(line('$')) !~ '^\s*$' 
	let bibdata = extend([''], bibdata)
    endif
    let bibdata = extend(bibdata, [''])
    call append(line('.'), bibdata)
    let g:atp_bibdata = bibdata

    call delete(atpbib_WgetOutputFile)
    return bibdata
endfunction
catch /E127/
endtry

command! -buffer -nargs=1 AMSRef    call <SID>GetAMSRef(<q-args>)
"}}}

" JMotion:
function! <SID>JMotion(flag) " {{{
    let pattern = '\%(\%(address\|annote\|author\|booktitle\|chapter\|crossref\|edition\|editor\|howpublished\|institution\|journal\|key\|month\|note\|number\|organization\|pages\|publisher\|school\|series\|title\|type\|volume\|year\|mrclass\|mrnumber\|mrreviewer\)\s*=\s.\zs\|@\w*\%({\|"\|(\|''\)\zs\)'
    call search(pattern, a:flag)
endfunction "}}}

" NEntry:
function! NEntry(flag,...) "{{{
    let keepjumps = ( a:0 >= 1 ? a:1 : "" )
    let pattern = '@\%(article\|book\%(let\)\=\|conference\|inbook\|incollection\|\%(in\)\=proceedings\|manual\|masterthesis\|misc\|phdthesis\|techreport\|unpublished\)'
"     let g:cmd = keepjumps . " call search(".pattern.",".a:flag.")" 
    keepjumps call search(pattern, a:flag)
    return line(".")
endfunction "}}}
 
" EntryEnd:
function! EntryEnd(flag) "{{{
    call NEntry("bc", "keepjumps")
    if a:flag =~# 'b'
	call NEntry("b", "keepjumps")
    endif
    keepjumps call search('\%({\|(\|"\|''\)')
    normal %
    return line(".")
endfunction "}}}

" Wrap:
"{{{
command! -buffer -nargs=* -complete=custom,atplib#various#BibWrapSelection_compl -range Wrap			:call atplib#various#WrapSelection(<f-args>)
if !hasmapto(":Wrap { } begin<cr>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_bracket_leader."{ 	:Wrap { } begin<CR>"
endif
if !hasmapto(":Wrap { } end<cr>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_bracket_leader."}	:Wrap { } end<CR>"
endif
if !hasmapto(":Wrap < > begin<cr>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_bracket_leader."< 	:Wrap < > begin<CR>"
endif
if !hasmapto(":Wrap < > end<cr>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_bracket_leader."> 	:Wrap < > end<CR>"
endif
if !hasmapto(":Wrap ( ) begin<cr>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_bracket_leader."( 	:Wrap ( ) begin<CR>"
endif
if !hasmapto(":Wrap ( ) end<cr>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_bracket_leader.") 	:Wrap ( ) end<CR>"
endif
if !hasmapto(":Wrap [ ] begin<cr>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_bracket_leader."[ 	:Wrap [ ] begin<CR>"
endif
if !hasmapto(":Wrap [ ] end<cr>", 'v')
    execute "vnoremap <silent> <buffer> ".g:atp_vmap_bracket_leader."] 	:Wrap [ ] end<CR>"
endif
"}}}

" Maps:
" {{{
nmap <buffer> <silent> ]]	:call NEntry("")<CR>
nmap <buffer> <silent> }	:call NEntry("")<CR>zz
nmap <buffer> <silent> [[	:call NEntry("b")<CR>
nmap <buffer> <silent> {	:call NEntry("b")<CR>zz

nmap <buffer> <silent> ][	:call EntryEnd("")<CR>
nmap <buffer> <silent> []	:call EntryEnd("b")<CR>

nmap <buffer> <c-j> 	:call <SID>JMotion("")<CR>
nmap <buffer> <c-k>	:call <SID>JMotion("b")<CR>	
imap <buffer> <c-j>	<Esc>l:call <SID>JMotion("")<CR>i
imap <buffer> <c-k>	<Esc>l:call <SID>JMotion("b")<CR>i

nnoremap <buffer> <silent> <F1>		:call system("texdoc bibtex")<CR>

nnoremap <buffer> <LocalLeader>a	:call append(line("."), g:atpbib_Article)<CR>:call <SID>JMotion("")<CR>
nnoremap <buffer> <LocalLeader>b	:call append(line("."), g:atpbib_Book)<CR>:call <SID>JMotion("")<CR>
nnoremap <buffer> <LocalLeader>bo	:call append(line("."), g:atpbib_Book)<CR>:call <SID>JMotion("")<CR>
nnoremap <buffer> <LocalLeader>c	:call append(line("."), g:atpbib_InProceedings)<CR>:call <SID>JMotion("")<CR>
nnoremap <buffer> <LocalLeader>bl	:call append(line("."), g:atpbib_Booklet)<CR>:call <SID>JMotion("")<CR>
nnoremap <buffer> <LocalLeader>ib	:call append(line("."), g:atpbib_InBook)<CR>:call <SID>JMotion("")<CR>
nnoremap <buffer> <LocalLeader>ic	:call append(line("."), g:atpbib_InCollection)<CR>:call <SID>JMotion("")<CR>
nnoremap <buffer> <LocalLeader>ma	:call append(line("."), g:atpbib_Manual)<CR>:call <SID>JMotion("")<CR>
nnoremap <buffer> <LocalLeader>mt	:call append(line("."), g:atpbib_MasterThesis)<CR>:call <SID>JMotion("")<CR>
nnoremap <buffer> <LocalLeader>mi	:call append(line("."), g:atpbib_Misc)<CR>:call <SID>JMotion("")<CR>
nnoremap <buffer> <LocalLeader>phd	:call append(line("."), g:atpbib_PhDThesis)<CR>:call <SID>JMotion("")<CR>
nnoremap <buffer> <LocalLeader>pr	:call append(line("."), g:atpbib_Proceedings)<CR>:call <SID>JMotion("")<CR>
nnoremap <buffer> <LocalLeader>tr	:call append(line("."), g:atpbib_TechReport)<CR>:call <SID>JMotion("")<CR>
nnoremap <buffer> <LocalLeader>un	:call append(line("."), g:atpbib_Unpublished)<CR>:call <SID>JMotion("")<CR>
" }}}
" vim:fdm=marker:tw=78:ff=unix:noet:ts=8:sw=4:fdc=1
ftplugin/bibsearch_atp.vim	[[[1
152
" Vim filetype plugin file
" Language:	tex
" Maintainer:	Marcin Szamotulski
" Last Change: Mon Oct 10, 2011 at 21:21:49  +0100
" Note:		This file is a part of Automatic Tex Plugin for Vim.

"
" {{{ Load Once
if exists("b:did_ftplugin") | finish | endif
let b:did_ftplugin = 1
" }}}

" Status Line:
function! ATPBibStatus() "{{{
    return substitute(expand("%"),"___","","g")
endfunction
setlocal statusline=%{ATPBibStatus()}
" }}}

" Maps:
" {{{ MAPS AND COMMANDS 
if !exists("no_plugin_maps") && !exists("no_atp_bibsearch_maps")
    map <buffer> <silent> c :<C-U>call <SID>BibYank(v:register,v:count)<CR>
    map <buffer> <silent> y :<C-U>call <SID>BibYank(v:register,v:count)<CR>
    map <buffer> <silent> p :<C-U>call <SID>BibPaste('p',v:count)<CR>
    map <buffer> <silent> P :<C-U>call <SID>BibPaste('P',v:count)<CR>
    map <buffer> <silent> q :hide<CR>
    command! -buffer -count -register -nargs=* Yank 	:call <SID>BibYank(<q-reg>,<q-count>)
    command! -buffer -count -nargs=* Paste 	:call <SID>BibPaste('p', <q-count>)
endif
" }}}

" Functions:
function! <SID>BibYank(register, which)" {{{
    " Yank selection to register
    let g:register = a:register
    let bibkey =  get(b:ListOfBibKeys, a:which, 'no_key') 
    if bibkey == 'no_key'
	echomsg "[ATP:] Did you specify the entry?"
	return
    endif
    let choice=substitute(strpart(bibkey, stridx(bibkey,'{')+1), ',', '', '')
    if a:register == 'a'
	let @a=choice
    elseif a:register == 'b'
	let @b=choice
    elseif a:register == 'c'
	let @c=choice
    elseif a:register == 'd'
	let @d=choice
    elseif a:register == 'e'
	let @e=choice
    elseif a:register == 'f'
	let @f=choice
    elseif a:register == 'g'
	let @g=choice
    elseif a:register == 'h'
	let @h=choice
    elseif a:register == 'i'
	let @i=choice
    elseif a:register == 'j'
	let @j=choice
    elseif a:register == 'k'
	let @k=choice
    elseif a:register == 'l'
	let @l=choice
    elseif a:register == 'm'
	let @m=choice
    elseif a:register == 'n'
	let @n=choice
    elseif a:register == 'o'
	let @o=choice
    elseif a:register == 'p'
	let @p=choice
    elseif a:register == 'q'
	let @q=choice
    elseif a:register == 'r'
	let @r=choice
    elseif a:register == 's'
	let @s=choice
    elseif a:register == 't'
	let @t=choice
    elseif a:register == 'u'
	let @u=choice
    elseif a:register == 'v'
	let @v=choice
    elseif a:register == 'w'
	let @w=choice
    elseif a:register == 'x'
	let @x=choice
    elseif a:register == 'y'
	let @y=choice
    elseif a:register == 'z'
	let @z=choice
    elseif a:register == '*'
	let @*=choice
    elseif a:register == '+'
	let @+=choice
    elseif a:register == '-'
	let @-=choice
    elseif a:register == '"'
	let @"=choice
    elseif a:register == ''
	if index(split(&cb, ','), 'unnamed') != -1
	    let @* = choice
	endif
	if index(split(&cb, ','), 'unnamedplus') != -1
	    let @+ = choice
	endif
    else
	let @" = choice
    endif
endfunction "}}}
function! <SID>BibPaste(command,...) "{{{
    if a:0 == 0 || a:0 == 1 && a:1 == 0
	let which	= input("Which entry? ( {Number}<Enter>, or <Enter> for none ) ")
	redraw
    else
	let which	= a:1
    endif
    if which == ""
	return
    endif
    let start	= stridx(b:ListOfBibKeys[which],'{')+1
    let choice	= substitute(strpart(b:ListOfBibKeys[which], start), ',\s*$', '', '')
    let @"	= choice

    " Goto right buffer
    let winbufnr = bufwinnr(b:BufNr)
    if winbufnr != -1
	exe "normal ".winbufnr."w"
    else
	if bufexist(b:BufNr)
	    exe "normal buffer ".winbufnr
	else
	    echohl WarningMsg 
	    echo "Buffer was deleted"
	    echohl None
	    return
	endif
    endif

    let LineNr 	= line(".")
    let ColNr 	= col(".") 
    if a:command ==# 'P'
	let ColNr -= 1
    endif
    call setline(LineNr, strpart(getline(LineNr), 0, ColNr) . choice . strpart(getline(LineNr), ColNr))
    call cursor(LineNr, len(strpart(getline(LineNr), 0, ColNr) . choice)+1)
    return
endfunction "}}}
" vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1
ftplugin/fd_atp.vim	[[[1
77
" Vim filetype plugin file
" Language:    tex
" Maintainer:  Marcin Szamotulski
" Last Change: Sun Sep 18, 2011 at 11:56  +0100
" Note:	       This file is a part of Automatic Tex Plugin for Vim.
"{{{ Load Once
if exists("b:did_ftplugin") | finish | endif
let b:did_ftplugin = 1
"}}}
"{{{ OpenFile
if !exists("*OpenFile")
function! OpenFile()
    let line	= max([line("."), '2'])-2
    let file	= g:fd_matches[line]

    " The list of fd files starts at second line.
    let openbuffer	= "topleft split! +setl\\ nospell\\ ft=fd_atp\\ noro " . fnameescape(file)
    silent exe openbuffer
    let b:atp_autex=0
endfunction
endif
"}}}
"{{{ ShowFonts
function! ShowFonts(fd_file)

    let font_commands	= atplib#fontpreview#ShowFonts(a:fd_file)

    let message		= ""
    for fcom in font_commands
	let message	.= "\n".fcom
    endfor
    let message="Fonts Declared:".message
    call confirm(message)
endfunction
"}}}
"{{{ Autocommand
augroup ATP_fd_list
    au CursorHold fd_list* :echo get(g:fd_matches, max([line("."),'2'])-2, "")
augroup END
"}}}
"{{{ Preview
function! Preview(keep_tex)

    let keep_tex = ( a:keep_tex == "!" ? 1 : 0 )

    let b_pos	= getpos("'<")[1]
    let e_pos	= getpos("'>")[1]

    if getpos("'<") != [0, 0, 0, 0] && getpos("'<") != [0, 0, 0, 0]
	let fd_files	= filter(copy(g:fd_matches),'index(g:fd_matches,v:val)+1 >= b_pos-1 && index(g:fd_matches,v:val)+1 <= e_pos-1')
    else
	let fd_files	= [g:fd_matches[(max([line("."),'2'])-2)]]
    endif

    call atplib#fontpreview#Preview(fd_files, keep_tex)

endfunction
"}}}
"{{{ Commands
if bufname("%") =~ 'fd_list'
    command! -buffer -bang -nargs=? -range Preview	:call Preview(<q-bang>, <f-args>)
    command! -buffer ShowFonts			:call ShowFonts(g:fd_matches[(max([line("."),'2'])-2)])
    map <buffer> <Enter> 			:call OpenFile()<CR>
    map <buffer> <Tab>				:call ShowFonts(g:fd_matches[(max([line("."),'2'])-2)])<CR>
else
    command! -buffer -nargs=1 Preview		:call atplib#fontpreview#Preview(["buffer"],<f-args>)
endif
"}}}
"{{{ Maps
map 	<buffer> 	P :Preview! <CR>
map 	<buffer> 	p :Preview <CR>
vmap 	<buffer> 	P :Preview! <CR>
vmap 	<buffer> 	p :Preview <CR>
map 	<buffer> 	Q :bd!<CR>
map 	<buffer> 	q :q!<CR>R
"}}}
" vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1
ftplugin/plaintex_atp.vim	[[[1
5
" Maintainer:	Marcin Szamotulski
" Note:		This file is a part of Automatic Tex Plugin for Vim.

" b:atp_TexFlavor will be set to plaintex automatically
runtime ftplugin/tex_atp.vim
ftplugin/tex_atp.vim	[[[1
114
" Title:		Vim filetype plugin file
" Author:		Marcin Szamotulski
" Web Page:		http://atp-vim.sourceforge.net
" Mailing List: 	atp-vim-list [AT] lists.sourceforge.net
" Do NOT DELETE the line just below, it is used by :UpdateATP (':help atp-:UpdateATP')
" Time Stamp: 15-05-12_07-18
" (but you can edit, if there is a reason for doing this. The format is dd-mm-yy_HH-MM)
" Language:	    tex
" Last Change: Tue Mar 20, 2012 at 15:55:38  +0000
" GetLatestVimScripts: 2945 62 :AutoInstall: tex_atp.vim
" GetLatestVimScripts: 884 1 :AutoInstall: AutoAlign.vim
" Copyright Statement: 
"     This file is a part of Automatic Tex Plugin for Vim.
"
"     Automatic Tex Plugin for Vim is free software: you can redistribute it
"     and/or modify it under the terms of the GNU General Public License as
"     published by the Free Software Foundation, either version 3 of the
"     License, or (at your option) any later version.
" 
"     Automatic Tex Plugin for Vim is distributed in the hope that it will be
"     useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
"     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
"     General Public License for more details.
" 
"     You should have received a copy of the GNU General Public License along
"     with Automatic Tex Plugin for Vim.  If not, see <http://www.gnu.org/licenses/>.
"
"     This licence applies to all files shipped with Automatic Tex Plugin.

" Do not source ATP if g:no_atp is set
if exists("g:no_atp") && g:no_atp == 1 || exists("b:did_ftplugin")
    finish
endif

let b:did_ftplugin	= 1
let g:loaded_AutomaticLatexPlugin = "11"

if !exists("g:atp_reload_functions")
	let g:atp_reload_functions = 0
endif
if !exists("g:atp_reload_variables")
	let g:atp_reload_variables = 0
endif

if &cpo =~# 'C'
    set cpo-=C
endif
let saved_cpo = &cpo
if &cpo =~ '<'
    setl cpo-=<
endif

	" Source Project Script
	runtime ftplugin/ATP_files/project.vim

	" ATPRC file overwrites project settings
	" (if the user put sth in atprc file, it means that he wants this globbaly) 
	call atplib#ReadATPRC()

	" Functions needed before setting options.
	runtime ftplugin/ATP_files/common.vim

	" Completion.
	runtime ftplugin/ATP_files/complete.vim

	" Options, global and local variables, autocommands.
	runtime ftplugin/ATP_files/options.vim

	runtime ftplugin/ATP_files/tex-fold.vim

	" Compilation related stuff.
	runtime ftplugin/ATP_files/compiler.vim

" 	let compiler_file = findfile('compiler/tex_atp.vim', &rtp)
" 	if compiler_file
" 		execute 'source ' 	. fnameescape(compiler_file)
" 	endif

	" LatexBox addons (by D.Munger, with some modifications).
	if g:atp_LatexBox

		runtime ftplugin/ATP_files/LatexBox_common.vim
		runtime ftplugin/ATP_files/LatexBox_complete.vim
		runtime ftplugin/ATP_files/LatexBox_motion.vim
		runtime ftplugin/ATP_files/LatexBox_latexmk.vim

	endif

	runtime ftplugin/ATP_files/motion.vim
	runtime ftplugin/ATP_files/search.vim
	runtime ftplugin/ATP_files/various.vim

	" Source maps and menu files.
	runtime ftplugin/ATP_files/mappings.vim

	if g:atp_LatexBox
		" LatexBox mappings.
		runtime ftplugin/ATP_files/LatexBox_mappings.vim
			
	endif

	" Source abbreviations.
	runtime ftplugin/ATP_files/abbreviations.vim

	" The menu.
	runtime ftplugin/ATP_files/menu.vim

	" Read ATPRC once again (to set mapps).
	call atplib#ReadATPRC()
	" Load Vim Settings from .tex.project file.

let &cpo=saved_cpo

" vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1
ftplugin/toc_atp.vim	[[[1
862
" Vim filetype plugin file
" Language:    tex
" Maintainer:  Marcin Szamotulski
" Last Change: Fri Apr 20, 2012 at 09:36:46  +0100
" Note:	       This file is a part of Automatic Tex Plugin for Vim.

" if exists("b:did_ftplugin") | finish | endif
let b:did_ftplugin = 1

function! ATP_TOC_StatusLine() " {{{
    return ( expand("%:t") == "__ToC__" ? "Table of Contents" : 
		\ ( expand("%:t") == "__Labels__" ? "List of Labels" : "" ) )
endfunction
setlocal statusline=%{ATP_TOC_StatusLine()}
" }}}

" {{{ <SID>GetLineNr(...)
" a:1 	line number to get, if not given the current line
" a:2	0/1 	0 (default) return linenr as for toc/labels
function! <SID>GetLineNr(...)
    let line 	=  a:0 >= 1 ? a:1 : line('.')
    let labels 	=  a:0 >= 2 ? a:2 : expand("%") == "__Labels__" ? 1 : 0

    if labels == 0
	return get(b:atp_Toc, line, ["", ""])[0:1]
    else
	return get(b:atp_Labels, line, ["", ""])[0:1]
    endif
endfunction
" command! -buffer GetLine :echo <SID>GetLineNr(line("."))
"}}}

function! s:getsectionnr(...) "{{{
    let line =  a:0 == 0 ? getline('.') : getline(a:1)
    return matchstr(l:line,'^\s*\d\+\s\+\zs\%(\d\|\.\)\+\ze\D')
endfunction
"}}}

" {{{1 s:gotowinnr
"---------------------------------------------------------------------
" Notes:
" 		(1) choose window with matching buffer name
" 		(2) choose among those which were edited last
" Solution:
"        			       --N-> choose this window
"			 	       |
"			     --N-> ----|
"			     | 	       --Y-> choose that window		
" --go from where you come-->|         Does there exist another open window 
"  			     |	       with the right buffer name?
"			     |	
"  			     --Y-> use this window
"			   Does the window have
"			   a correct name?
"
" This function returns the window number to which we will eventually go.
function! s:gotowinnr()
    let labels_window	= ( expand("%") == "__Labels__" ? 1 : 0 )

    " This is the line number to which we will go.
    let [ l:bufname, l:nr ] =atplib#tools#getlinenr(line("."), labels_window)

    if labels_window
	" Find labels window to go in Labels window
	let l:gotowinnr=bufwinnr(l:bufname)
    else
	" Find labels window to go in ToC window
	if t:atp_bufname == l:bufname
	    " if t:atp_bufname agree with that found in ToC
	    " if the t:atp_winnr is still open
	    let l:gotowinnr=bufwinnr(l:bufname)
	else
	    if bufwinnr("^" . l:bufname . "$") != 0
		" if not but there is a window with buffer l:bufname
		let l:gotowinnr=bufwinnr("^" . l:bufname . "$")
	    else
		" if not and there is no window with buffer l:bufname
		let l:gotowinnr=t:atp_winnr
	    endif
	endif
    endif

    return l:gotowinnr
endif
endfunction
command! -buffer GotoWinNr	:echo s:gotowinnr()
" }}}1

function! GotoLine(closebuffer) "{{{
    let labels_window	= expand("%") == "__Labels__" ? 1 : 0
    
    " if under help lines do nothing:
    let toc		= getbufline("%",1,"$")
    let h_line		= index(reverse(copy(toc)),'')+1
    if line(".") > len(toc)-h_line
	return ''
    endif

    " remember the ToC window number
    let tocbufnr= bufnr("")

    " line to go to
    let [file,nr] = atplib#tools#getlinenr(line("."), labels_window)

    " window to go to
    let gotowinnr= s:gotowinnr()

    if gotowinnr != -1
 	exe gotowinnr . " wincmd w"
	if fnamemodify(file, ":p") != fnamemodify(bufname("%"), ":p")
	    exe "e " . fnameescape(file)
	endif
    else
 	exe "wincmd w"
	exe "e " . fnameescape(file)
    endif
	
    "if we were asked to close the window
    if a:closebuffer == 1
	exe "bdelete " . tocbufnr
    endif

    "finally, set the position
    call setpos("''", getpos("."))
    call setpos('.', [0, nr, 1, 0])
    exe "normal zt"
    
endfunction
" }}}

function! <SID>yank(arg, ...) " {{{
    let time = reltime()
    let labels_window	= expand("%") == "__Labels__" ? 1 : 0
    let register	= ( a:0 >= 1 ? a:1 : v:register )

    let l:toc=getbufline("%",1,"$")
    let l:h_line=index(reverse(copy(l:toc)),'')+1
    if line(".") > len(l:toc)-l:h_line
	return ''
    endif

    let l:cbufnr=bufnr("")
    let [ file_name, line_nr ] = atplib#tools#getlinenr(line("."), labels_window)

    if !labels_window
	if !exists("t:atp_labels") || index(keys(t:atp_labels), file_name) == -1
	    " set t:atp_labels variable
            if g:atp_python_toc
                call atplib#tools#generatelabels(get(b:atp_Toc, line("."), ["", "", ""])[2], 0)
            else
                call atplib#tools#generatelabels(getbufvar(file_name, 'atp_MainFile'), 0)
            endif
	endif

	let choice	= get(get(filter(get(deepcopy(t:atp_labels), file_name, []), 'v:val[0] ==  line_nr'), 0, []), 1 , 'nokey')
    else
        if exists("t:atp_labels")
	    let choice_list	= filter(get(deepcopy(t:atp_labels), file_name, []), "v:val[0] == line_nr" )
	    " There should be just one element in the choice list
	    " unless there are two labels in the same line.
	    let choice	= choice_list[0][1]
	else
	    let choice	= "nokey"
	endif
    endif

    if choice	== "nokey"
	" in TOC, if there is a key we will give it back if not:
	au! CursorHold __ToC__
	echomsg "[ATP:] there is no key."
	sleep 750m
	au CursorHold __ToC__ :call EchoLine()
	return ""
    else
	if a:arg == '@'
	    silent if register == 'a'
		let @a=choice
	    elseif register == 'b'
		let @b=choice
	    elseif register == 'c'
		let @c=choice
	    elseif register == 'd'
		let @d=choice
	    elseif register == 'e'
		let @e=choice
	    elseif register == 'f'
		let @f=choice
	    elseif register == 'g'
		let @g=choice
	    elseif register == 'h'
		let @h=choice
	    elseif register == 'i'
		let @i=choice
	    elseif register == 'j'
		let @j=choice
	    elseif register == 'k'
		let @k=choice
	    elseif register == 'l'
		let @l=choice
	    elseif register == 'm'
		let @m=choice
	    elseif register == 'n'
		let @n=choice
	    elseif register == 'o'
		let @o=choice
	    elseif register == 'p'
		let @p=choice
	    elseif register == 'q'
		let @q=choice
	    elseif register == 'r'
		let @r=choice
	    elseif register == 's'
		let @s=choice
	    elseif register == 't'
		let @t=choice
	    elseif register == 'u'
		let @u=choice
	    elseif register == 'v'
		let @v=choice
	    elseif register == 'w'
		let @w=choice
	    elseif register == 'x'
		let @x=choice
	    elseif register == 'y'
		let @y=choice
	    elseif register == 'z'
		let @z=choice
	    elseif register == '*'
		let @-=choice
	    elseif register == '+'
		let @+=choice
	    elseif register == '-'
		let @@=choice
	    endif
	elseif a:arg == 'p'

	    let l:gotowinnr=s:gotowinnr()
	    exe l:gotowinnr . " wincmd w"

	    " delete the buffer
" 	    exe "bdelete " . l:cbufnr

	    " set the line
	    let l:line=getline('.')
	    let l:colpos=getpos('.')[2]
	    if a:arg ==# 'p'
		let l:bline=strpart(l:line, 0, l:colpos)
		let l:eline=strpart(l:line, l:colpos)
	    else
		let l:bline=strpart(l:line, 0, l:colpos-1)
		let l:eline=strpart(l:line, l:colpos-1)
	    endif
	    call setline('.',l:bline . choice . l:eline)
	    call setpos('.',[getpos('.')[0],getpos('.')[1],getpos('.')[2]+len(choice),getpos('.')[3]])
	endif
    endif
    let g:time_yank=reltimestr(reltime(time))
endfunction
command! -buffer P :call Yank("p")
" }}}

if !exists("*YankToReg")
function! YankToReg()
    call <SID>yank("@", v:register)
endfunction
endif

if !exists("*Paste")
function! Paste()
    call <SID>yank("p")
endfunction
endif

" Show Label Context 
" {{{1 ShowLabelContext
if !exists("*ShowLabelContext")
function! ShowLabelContext(height)
    let labels_window	= ( expand("%:t") == "__Labels__" ? 1 : 0 )

    let toc	= getbufline("%",1,"$")
    let h_line	= index(reverse(copy(toc)),'')+1
    if line(".") > len(toc)-h_line
	return ''
    endif

    let cbuf_name	= bufname('%')
    let [buf_name, line] = atplib#tools#getlinenr(line("."), labels_window)
    wincmd w
    let buf_nr		= bufnr("^" . buf_name . "$")
    let height		= ( !a:height ? "" : a:height )
    " Note: using split without argument is faster than split #{bufnr} or 
    " split {bufname}.
    if buf_nr == bufnr("%")
	let splitcmd = height."split"
    elseif buf_nr != -1
	let splitcmd = height."split #" . buf_nr
    else
	let splitcmd = height."split " . buf_name
    endif
    silent exe splitcmd
    call setpos('.', [0, line, 1, 0])
    if !labels_window
	exe "normal! zt"
    endif
endfunction
endif
" }}}1
" Echo line
" {{{1 EchoLine
if !exists("*EchoLine")
function! EchoLine()
    " Note: only shows the line of loaded buffers (loading buffer takes some
    " time)

    " If we are not on a toc/label line 
    " return
    if atplib#tools#getlinenr(line(".")) == ['', '']
	return 0
    endif

    let labels_window	= expand("%") == "__Labels__" ? 1 : 0

    let toc		= getbufline("%",1,"$")
    let h_line		= index(reverse(copy(toc)),'')+1
"     if line(".") > len(toc)-h_line
" 	return 0
"     endif

    let [buf_name,line] = atplib#tools#getlinenr(line("."), labels_window)
    let buf_nr		= bufnr("^" . buf_name . "$")
    if labels_window && !exists("t:atp_labels")
	let t:atp_labels[buf_name]	= UpdateLabels(buf_name)[buf_name]
    endif
    if buf_nr != -1
	let sec_line	= get(getbufline(buf_name,line),0,"")
    else
	let sec_line	= get(readfile(buf_name),line-1,"")
    endif
    let i 		= 1
    while sec_line	!~ '\\\%(\%(sub\)\?paragraph\|\%(sub\)\{0,2}section\|chapter\|part\)\s*{.*}' && i <= 20
	let sec_line	= substitute(sec_line, '\s*$', '', '') . substitute(join(getbufline(buf_name, line+i)), '^\s*', ' ', '')
	let i 		+= 1
    endwhile
    let sec_type	= ""

    if sec_line =~ '\\subparagraph[^\*]'
	let sec_type="subparagraph  "
    elseif sec_line =~ '\\subparagraph\*'
	let sec_type="subparagraph* "
    elseif sec_line =~ '\\paragraph[^\*]'
	let sec_type="paragraph     "
    elseif sec_line =~ '\\paragraph\*'
	let sec_type="paragraph*    "
    elseif sec_line =~ '\\subsubsection[^\*]'
	let sec_type="subsubsection "
    elseif sec_line =~ '\\subsubsection\*'
	let sec_type="subsubsection*"
    elseif sec_line =~ '\\subsection[^\*]'
	let sec_type="subsection    "
    elseif sec_line =~ '\\subsection\*'
	let sec_type="subsection*   "
    elseif sec_line =~ '\\section[^\*]'
	let sec_type="section       "
    elseif sec_line =~ '\\section\*'
	let sec_type="section*      "
    elseif sec_line =~ '\\chapter[^\*]'
	let sec_type="chapter       "
    elseif sec_line =~ '\\chapter\*'
	let sec_type="chapter*      "
    elseif sec_line =~ '\\part[^\*]'
	let sec_type="part          "
    elseif sec_line =~ '\\part\*'
	let sec_type="part*         "
    elseif sec_line =~ '\\bibliography'
	let sec_type="bibliography  "
    elseif sec_line =~ '\\abstract\|\\begin\s*{\s*abstract\s*}'
	let sec_type="abstract      "
    elseif sec_line =~ '\\documentclass'
	let sec_type="preambule     "
    endif
    let sec_type = toupper(sec_type)
    if expand("%") == "__Labels__"
	let sec_type="TYPE " 
    endif

    let label		= matchstr(sec_line,'\\label\s*{\zs[^}]*\ze}')
    let section		= strpart(sec_line,stridx(sec_line,'{')+1,stridx(sec_line,'}')-stridx(sec_line,'{')-1)
    if section != "" && label != ""
	echo sec_type . " : '" . section . "'\t label : " . label
    elseif section != ""
	echo sec_type . " : '" . section . "'"
    else
	echo ""
    endif
    return 1
endfunction
endif
setl updatetime=200 
augroup ATP_TOC
    au!
    au CursorHold __ToC__ :call EchoLine()
augroup END
"}}}1

" Compare Numbers Function {{{1
function! s:CompareNumbers(i1, i2)
    return str2nr(a:i1) == str2nr(a:i2) ? 0 : str2nr(a:i1) > str2nr(a:i2) ? 1 : -1
endfunction "}}}1

" YankSection, DeleteSection, PasteSection, SectionStack, Undo.
" {{{1
" Stack of sections that were removed but not yet paste
" each entry is a list [ section title , list of deleted lines, section_nr ]
" where the section title is the one from t:atp_toc[filename][2]
" section_nr is the section number before deletion
" the recent positions are put in the front of the list
if expand("%") == "__ToC__" &&
	    \ ( !g:atp_python_toc || g:atp_devversion )
    if !exists("t:atp_SectionStack")
	let t:atp_SectionStack 	= []
    endif

    function! <SID>SectionScope()
	" Return [ file, begin_line, end_line, title, type, section_nr, bibliography ] or ['', '', '', '', '', '', '']  if error.

	" Get the name and path of the file
	" to operato on
	let [file_name,begin_line]	= atplib#tools#getlinenr()
	let section_nr			= s:getsectionnr()
	if g:atp_python_toc
	    let main_file	= get(b:atp_Toc, line("."), ["", "", ""])[2]
	    let toc		= deepcopy(t:atp_pytoc[main_file]) 
	    let type		= ""
	    let toc_entry	= ['', '', '', '', '', '', ''] 
	    let ind		= 0
	    for toc_entry in toc
		if toc_entry[0:1] == [file_name, begin_line]
		    let type	= toc_entry[2]
		    break
		endif
		let ind+=1
	    endfor
	else
	    let toc		= deepcopy(t:atp_toc[file_name]) 
	    let type		= toc[begin_line][0]
	endif

	" Only some types are supported:
	if index(['bibliography', 'subsubsection', 'subsection', 'section', 'chapter', 'part'], type) == -1
	    echo "Section type: " . type . " is not supported"
	    sleep 750m
	    return ['', '', '', '', '', '', '']
	endif

	" Find the end of the section:
	" part 		is ended by part
	" chapter		is ended by part or chapter
	" section		is ended by part or chapter or section
	" and so on,
	" bibliography 	is ended by like subsubsection.
	if type == 'part'
	    let type_pattern = 'part\|bibliography'
	elseif type == 'chapter'
	    let type_pattern = 'chapter\|part\|bibliography'
	elseif type == 'section'
	    let type_pattern = '\%(sub\)\@<!section\|chapter\|part\|bibliography'
	elseif type == 'subsection'
	    let type_pattern = '\%(sub\)\@<!\%(sub\)\=section\|chapter\|part\|bibliography'
	elseif type == 'subsubsection' || type == 'bibliography'
	    let type_pattern = '\%(sub\)*section\|chapter\|part\|bibliography'
	endif
	if g:atp_python_toc
	    let title	= toc_entry[3]
	    let toc	= toc[ind+1:]
	    " We will search for end line only in the same file:
	    call filter(toc, "v:val[0] == file_name")
	else
	    let title		= toc[begin_line][2]
	    call filter(toc, 'str2nr(v:key) > str2nr(begin_line)')
	endif
	let end_line 		= -1
	let bibliography	=  0

	if g:atp_python_toc
	    for toc_e in toc
		if toc_e[2] =~ type_pattern
		    let end_line = toc_e[1]-1
		    if toc_e[2] =~ 'bibliography'
			let bibliography = 1
		    endif
		    break
		endif
	    endfor
	else
	    for line in sort(keys(toc), "s:CompareNumbers")
		if toc[line][0] =~ type_pattern
		    let end_line = line-1
		    if toc[line][0] =~ 'bibliography'
			let bibliography = 1
		    endif
		    break
		endif
	    endfor
	endif

	if end_line == -1 && &l:filetype == "plaintex"
	    " TODO:
	    echomsg "[ATP:] can not yank last section in plain tex files :/"
	    sleep 750m
	    return ['', '', '', '', '', '', '']
	endif
	return [ file_name, begin_line, end_line, title, type, section_nr, bibliography]
    endfunction

    function! <SID>YankSection(...)

	let register = ( a:0 >= 1 ? '"'.a:1 : '' ) 

	" if under help lines do nothing:
	let toc_line	= getbufline("%",1,"$")
	let h_line	= index(reverse(copy(toc_line)),'')+1
	if line(".") > len(toc_line)-h_line
	    return ''
	endif

	let s:deleted_section = toc_line

	let [file_name, begin_line, end_line, title, type, section_nr, bibliography] = <SID>SectionScope()
	if [file_name, begin_line, end_line, title, type, section_nr, bibliography] == ['', '', '', '', '', '']
	    return
	endif

	" Window to go to
	let toc_winnr	= winnr()
	let gotowinnr	= s:gotowinnr()

	if gotowinnr != -1
	    exe gotowinnr . " wincmd w"
	    let winview	= winsaveview()
	    let bufnr = bufnr("%")
	else
" 	    exe gotowinnr . " wincmd w"
	    exe "wincmd w"
	    let bufnr = bufnr("%")
	    let winview	= winsaveview()
	    exe "e " . fnameescape(file_name)
	endif
	    
	"Finally, set the position:
	keepjumps call setpos('.',[0,begin_line,1,0])
	normal! V
	if end_line != -1 && !bibliography
	    keepjumps call setpos('.',[0, end_line, 1, 0])
	elseif bibliography
	    keepjumps call setpos('.',[0, end_line, 1, 0])
	    let end_line 	= search('^\s*$', 'cbnW')-1
	elseif end_line == -1
	    let end_line 	= search('\ze\\end\s*{\s*document\s*}')
	    normal! ge
	endif

	execute 'normal '.register.'y'
	if bufnr != -1
	    execute "buffer ".bufnr
	endif
	call winrestview(winview)
	execute toc_winnr . "wincmd w"
	execute "let yanked_section=@".register
	let yanked_section_list= split(yanked_section, '\n')
	if yanked_section_list[0] !~ '^\s*$' 
	    call extend(yanked_section_list, [''], 0)  
	endif
	call extend(t:atp_SectionStack, [[title, type, yanked_section_list, section_nr, file_name]],0)
    endfunction
    command! -buffer -nargs=? YankSection	:call <SID>YankSection(<f-args>)

    function! <SID>DeleteSection()

	" if under help lines do nothing:
	let toc_line	= getbufline("%",1,"$")
	let h_line	= index(reverse(copy(toc_line)),'')+1
	if line(".") > len(toc_line)-h_line
	    return ''
	endif

	let s:deleted_section = toc_line

	let [file_name, begin_line, end_line, title, type, section_nr, bibliography] = <SID>SectionScope()
	if [file_name, begin_line, end_line, title, type, section_nr, bibliography] == ['', '', '', '', '', '']
	    return
	endif

	" Window to go to
	let gotowinnr	= s:gotowinnr()

	if gotowinnr != -1
	    exe gotowinnr . " wincmd w"
	else
" 	    exe gotowinnr . " wincmd w"
	    exe "wincmd w"
	    exe "e " . fnameescape(file_name)
	endif
	    
	"finally, set the position
	call setpos('.',[0,begin_line,1,0])
	normal! V
	if end_line != -1 && !bibliography
	    call setpos('.',[0, end_line, 1, 0])
	elseif bibliography
	    call setpos('.',[0, end_line, 1, 0])
	    let end_line 	= search('^\s*$', 'cbnW')-1
	elseif end_line == -1
	    let end_line 	= search('\ze\\end\s*{\s*document\s*}')
	    normal! ge
	endif
	" and delete
	normal d
	let deleted_section	= split(@*, '\n')
	if deleted_section[0] !~ '^\s*$' 
	    call extend(deleted_section, [''], 0)  
	endif

	" Update the Table of Contents
	if !g:atp_python_toc
	    call remove(t:atp_toc[file_name], begin_line)
	    let new_toc={}
	    for line in keys(t:atp_toc[file_name])
		if str2nr(line) < str2nr(begin_line)
		    call extend(new_toc, { line : t:atp_toc[file_name][line] })
		else
		    call extend(new_toc, { line-len(deleted_section) : t:atp_toc[file_name][line] })
		endif
	    endfor
	    let t:atp_toc[file_name]	= new_toc
	endif
	" Being still in the tex file make backup:
	if exists("g:atp_SectionBackup")
	    call extend(g:atp_SectionBackup, [[title, type, deleted_section, section_nr, expand("%:p")]], 0)
	else
	    let g:atp_SectionBackup	= [[title, type, deleted_section, section_nr, expand("%:p")]]
	endif
	" return to toc 
	TOC! 0

	" Update the stack of deleted sections
	call extend(t:atp_SectionStack, [[title, type, deleted_section, section_nr, file_name]],0)
    endfunction
    command! -buffer DeleteSection	:call <SID>DeleteSection()
    " nnoremap dd			:call <SID>DeleteSection()<CR>

    " Paste the section from the stack
    " just before where the next section starts.
    " type = p/P	like paste p/P.
    " a:1	- the number of the section in the stack (from 1,...)
    " 	- by default it is the last one.
    function! <SID>PasteSection(type, ...)

	let stack_number = a:0 >= 1 ? a:1-1 : 0 

	if !len(t:atp_SectionStack)
	    sleep 750m
	    echomsg "[ATP:] the stack of deleted sections is empty"
	    return
	endif

	if a:type ==# "P" || line(".") == 1
	    let [buffer, begin_line]	= atplib#tools#getlinenr((line(".")))
	else
	    let [buffer, begin_line]	= atplib#tools#getlinenr((line(".")+1))
	    if begin_line	== ""
		let begin_line	= "last_line"
	    endif
	endif

	" Window to go to
	let gotowinnr	= s:gotowinnr()

	if gotowinnr != -1
	    exe gotowinnr . " wincmd w"
	else
	    exe "wincmd w"
	    exe "e " . fnameescape(buffer)
	endif

	if begin_line != ""
	    if begin_line != "last_line"
		call setpos(".", begin_line-1)
	    else
		keepjumps call setpos(".", [0, line("$"), 1, 0])
		keepjumps exe "normal $"
		keepjumps call search('\n.*\\end\s*{\s*document\s*}', 'bW')
		let begin_line = line(".")
	    endif
	elseif &l:filetype != 'plaintex'
	    keepjumps let begin_line	= search('\\end\s*{\s*document\s*}', 'nw')
	else
	    echo "Pasting at the end is not supported for plain tex documents"
	    return
	endif
	let number	= len(t:atp_SectionStack)-1
	" Append the section
	call append(begin_line-1, t:atp_SectionStack[stack_number][2])
	" Set the cursor position to the begining of moved section and add it to
	" the jump list
	call setpos(".", [0, begin_line, 1, 0])

	" Regenerate the Table of Contents:
	TOC!

	" Update the stack
	call remove(t:atp_SectionStack, stack_number)
    endfunction
    command! -buffer -nargs=? -bang PasteSection	:call <SID>PasteSection((<q-bang> == '!' ? 'P' : 'p'), <f-args>)

    " Lists title of sections in the t:atp_SectionStack
    function! <SID>SectionStack()
	if len(t:atp_SectionStack) == 0
	    echomsg "[ATP:] section stack is empty"
	    sleep 750m
	    return
	endif
	let i	= 1
	echohl WarningMsg
	echo "Number\tType\t\t\tTitle\t\t\t\t\tFile"
	echohl Normal
	let msg = []
	for section in t:atp_SectionStack
	    call add(msg, i . "\t" .  section[1] . " " . section[3] . "\t\t" . section[0]."\t\t".fnamemodify(section[4], ':.'))
	    let i+=1
	endfor
	" There is CursorHold event in toc list which showes the line,
	" using input() the message will not disapear imediately.
	call input(join(msg + [ "Press <Enter>" ] , "\n"))
    endfunction
    command! -buffer SectionStack	:call <SID>SectionStack()

    " Undo in the winnr under the cursor.
    " a:1 is one off u or U, default is u.
    function! <SID>Undo(...)
	let cmd	= ( a:0 >= 1 && a:1 =~ '\cu\|g\%(-\|+\)' ? a:1 : 'u' )
	let winnr	= s:gotowinnr()
	exe winnr . " wincmd w"
	exe "normal! " . cmd
	TOC!
    endfunction
    command! -buffer -nargs=? Undo 	:call <SID>Undo(<f-args>) 
    nnoremap <buffer> u			:call <SID>Undo('u')<CR>
    nnoremap <buffer> U			:call <SID>Undo('U')<CR>
    nnoremap <buffer> g-		:call <SID>Undo('g-')<CR>
    nnoremap <buffer> g+		:call <SID>Undo('g+')<CR>
endif
" }}}1

function! Help() " {{{1
    " Note: here they are not well indented, but in the output they are :)
    echo "Available Mappings:"
    echo "q 			close ToC window"
    echo "<CR>  			go to and close"
    echo "<space>			go to"
    echo "c or y			yank the label to a register"
    echo "p or P			yank and paste the label (in the source file)"
    echo "e			echo the title to command line"
    if expand("%")  == "__ToC__"
	echo ":YankSection [reg]	Yank section under the cursor to register"
	echo "                  	  (by default to the unnamed register \")"
	echo ":DeleteSection		Delete section under the cursor"
	echo ":PasteSection [arg] 	Paste section from section stack"
	echo ":SectionStack		Show section stack"
	echo ":Undo			Undo"
    endif
    echo "<F1>			this help message"
endfunction " }}}1

" ATP_CursorLine autocommand:
" {{{1
augroup ATP_CursorLine
    au CursorMoved,CursorMovedI __ToC__ call atplib#tools#CursorLine()
augroup END 
" }}}1

" Fold section
" {{{1
func! CompareNumbers(i1, i2)
    return str2nr(a:i1) == str2nr(a:i2) ? 0 : str2nr(a:i1) > str2nr(a:i2) ? 1 : -1
endfunc
function! Section2Nr(section)
    if a:section == 'part'
	return 1
    elseif a:section == 'chapter'
	return 2
    elseif a:section == 'section' || a:section == 'abstract'
	return 3
    elseif a:section == 'subsection'
	return 4
    elseif a:section == 'paragraph'
	return 5
    elseif a:section == 'subparagraph'
	return 6
    else
	return 7
    endif
endfunction
" }}}1
function! FoldClose(...) " {{{1
    let atp_toc	= deepcopy(t:atp_toc)
    let f_line = (a:0 >= 1 ? a:1 : line(".") )
    let l_line = (a:0 >= 2 ? a:2 : line(".") )
    " This function is not working well with sections put into chapters. Then
    " chapters are not folded with greater fold level.
    for line in range(f_line, l_line)
	let [beg_file,beg_line] = <sid>GetLineNr(line)
	let type = <SID>Section2Nr(get(get(deepcopy(atp_toc), file, {}), beg_line, [''])[0])
	let type_dict = get(deepcopy(atp_toc), beg_file, {})
	call filter(map(type_dict, "<SID>Section2Nr(v:val[0])"), "str2nr(v:val) <= str2nr(type)")
	let line_list = sort(filter(keys(type_dict), "str2nr(v:val) >= str2nr(beg_line)"), "<SID>CompareNumbers")
	let [end_file,end_line] = <SID>GetLineNr(line(".")+1)
	" Goto file
	let winnr = s:gotowinnr()
	let toc_winnr = winnr()
	exe winnr."wincmd w"
	let end_line = get(line_list, 1, "")
	if end_line != ""
	    let end_line = end_line-1
	else
	    let end_line = line("$")
	endif
	echomsg beg_line." ".end_line
	execute beg_line.",".end_line."fold"
	exe toc_winnr."wincmd w"
    endfor
endfunction " }}}1

" Mappings:
" MAPPINGS {{{1
if !exists("no_plugin_maps") && !exists("no_atp_toc_maps")
    command! -range Fold		:call FoldClose(<q-line1>,<q-line2>)
    nmap <silent> <buffer> zc		:call FoldClose()<CR>
    vmap <silent> <buffer> zc		:<C-U>call FoldClose(line("'<"), line("'>"))<CR>
    map <silent> <buffer> q 		:bdelete<CR>
    map <silent> <buffer> <CR> 		:call GotoLine(1)<CR>
    map <silent> <buffer> <space> 	:call GotoLine(0)<CR>
    map <silent> <buffer> <LeftRelease>   <LeftMouse><bar>:call GotoLine(0)<CR>
    if expand("%") == "__ToC__"
	map <silent> <buffer> _		:call GotoLine(0)<bar>wincmd w<CR>
    else
	map <silent> <buffer> _		:call GotoLine(0)<bar>Labels<CR>
    endif
" This does not work: 
"   noremap <silent> <buffer> <LeftMouse> :call GotoLine(0)<CR>
"   when the cursor is in another buffer (and the option mousefocuse is not
"   set) it calles the command instead of the function, I could add a check if
"   mouse is over the right buffer. With mousefocuse it also do not works very
"   well.
    map <silent> <buffer> c		:call YankToReg()<CR>
    map <silent> <buffer> y 		:call YankToReg()<CR>
    map <silent> <buffer> p 		:call Paste()<CR>
    map <silent> <buffer> P 		:call <SID>yank("P")<CR>
    map <silent> <buffer> s 		:<C-U>call ShowLabelContext(v:count)<CR> 
    map <silent> <buffer> e 		:call EchoLine()<CR>
    map <silent> <buffer> <F1>		:call Help()<CR>
endif
" vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1
indent/tex.vim	[[[1
83
" Title:	vim indent file for tex files.
" Author: 	David Munger (mungerd@gmail.com)
" Maintainer:	Marcin Szamotulski
" Note:		This file is a part of Automatic Tex Plugin for Vim.
" Language:	tex
" Last Change:

if exists("b:did_indent") || ( exists("g:atp_indent") && !g:atp_indent )
    finish
endif

let b:did_indent = 1

setlocal indentexpr=LatexBox_TexIndent()
setlocal indentkeys==\end,=\item,),],},o,O,0\\,!^F 

let s:itemize_envs = ['itemize', 'enumerate', 'description']

" indent on \left( and on \(, but not on (
" indent on \left[ and on \[, but not on [
" indent on \left\{ and on \{, and on {
let s:open_pat = '\\begin\>\|\%(\\left\s*\)\=\\\=[{]\|\%(\\left\s*\|\\\)[[(]'
let s:close_pat = '\\end\>\|\%(\\right\s*\)\=\\\=[}]\|\%(\\right\s*\|\\\)[])]'


" Compute Level {{{
function! s:ComputeLevel(lnum_prev, open_pat, close_pat)

	let n = 0

	let line_prev = getline(a:lnum_prev)

	" strip comments
	let line_prev = substitute(line_prev, '\\\@<!%.*', '', 'g')

	" find unmatched opening patterns on previous line
	let n += len(substitute(substitute(line_prev, a:open_pat, "\n", 'g'), "[^\n]", '', 'g'))
	let n -= len(substitute(substitute(line_prev, a:close_pat, "\n", 'g'), "[^\n]", '', 'g'))

	" reduce indentation if current line starts with a closing pattern
	if getline(v:lnum) =~ '^\s*\%(' . a:close_pat . '\)'
		let n -= 1
	endif

	" compensate indentation if previous line starts with a closing pattern
	if line_prev =~ '^\s*\%(' . a:close_pat . '\)'
		let n += 1
	endif

	return n
endfunction
" }}}

" TexIndent {{{
function! LatexBox_TexIndent()

	let lnum_prev = prevnonblank(v:lnum - 1)

	if lnum_prev == 0
		return 0
	endif

	let n = 0

	let n += s:ComputeLevel(lnum_prev, s:open_pat, s:close_pat)

	let n += s:ComputeLevel(lnum_prev, '\\begin{\%(' . join(s:itemize_envs, '\|') . '\)}', 
		    \ '\\end{\%(' . join(s:itemize_envs, '\|') . '\)}')

	" less shift for lines starting with \item
	let item_here = getline(v:lnum) =~ '^\s*\\item'
	let item_above = getline(lnum_prev) =~ '^\s*\\item'
	if !item_here && item_above
		let n += 1
	elseif item_here && !item_above
		let n -= 1
	endif

	return indent(lnum_prev) + n * &sw
endfunction
" }}}

" vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1
plugin/tex_atp.vim	[[[1
164
" Title:		Vim plugin file of Automatix LaTex Plugin
" Author:		Marcin Szamotulski
" Web Page:		http://atp-vim.sourceforge.net
" Mailing List: 	atp-vim-list [AT] lists.sourceforge.net

" Note: autocommand events BufRead, BufAdd are not executed from ftplugin
" directory, they should all should be here. Loading once on startup when
" filetype is set, may be achived using:
"    au BufRead *.tex au! BufEnter *.tex :call Function()
"    \

" KpsewhichEdit command: {{{1
function! <SID>KpsewhichEdit(args)
    let [ string, edit_args, file]  = matchlist(a:args, '\(.\{-}\)\s*\(\f\+\)$')[0:2]
    let file_path = matchstr(system("kpsewhich '".file."'"),'^.*\ze\n')
    if empty(file_path)
	echohl WarningMsg | echo "Kpsewhich cannot find the file: ".file | echohl Normal
    else
	exe "edit ".escape(edit_args, '\ ')." ".fnameescape(file_path)
    endif
    " Setting filetype=plaintex leads to errors.
endfunction
function! <SID>KpsewhichEditComp(ArgLead, CmdLine, CursorPos)
    let completion_list = []
    if exists("g:atp_LatexPackages")
" 	let g:atp_LatexPackages	= atplib#search#KpsewhichGlobPath("tex", "", "*.sty")
	call extend(completion_list, map(deepcopy(g:atp_LatexPackages), 'v:val.".sty"'))
    endif
    if exists("g:atp_LatexClasses")
" 	let g:atp_LatexClasses	= atplib#search#KpsewhichGlobPath("tex", "", "*.cls")
	call extend(completion_list, map(deepcopy(g:atp_LatexClasses), 'v:val.".cls"'))
    endif
    return join(completion_list, "\n")
endfunction
command! -nargs=1 -complete=custom,<SID>KpsewhichEditComp KpsewhichEdit :call <SID>KpsewhichEdit('<args>')
augroup ATP_LoadVimSettings "{{{1
    " In this way settings from project.vim script will overwrite vimrc file.
    au!
    au! BufRead *.tex :au BufEnter *.tex :call ATP_LoadVimSettings()
augroup END

" Set options and maps for tex log file.
function! TexLogCurrentFile() " {{{1
    let saved_pos = getpos(".")
    let savedview = winsaveview()
    let skip = 'getline(".") =~ ''^l\.\d\+.*'' || getline(line(".")-1) =~ ''^l\.\d\+.*'' && getline(".") =~ ''^\s\+'' || getline(line(".")-1) =~ ''^Runaway argument?'' || getline(line(".")-1) =~ ''^\(Over\|Under\)full\>'''
    let skip=""
    call searchpair('(', '', ')', 'cbW', skip)
    let file = matchstr(getline(".")[col("."):], '^\f*')
    if filereadable(file)
	call setpos(".", saved_pos)
	call winrestview(savedview) 
	return file
    else
	call searchpair('(', '', ')', 'bW', skip)
	let file = matchstr(getline(".")[col("."):], '^\f*')
	call setpos(".", saved_pos)
	call winrestview(savedview) 
	call setpos(".", saved_pos)
	call winrestview(savedview) 
	if filereadable(file)
	    return file
	else
	    return ""
	endif
    endif
endfunction
function! <SID>TexLogSettings(fname) "{{{1
    " This function should also have the SyncTex section of
    " atplib#various#OpenLog, but since it requires b:atp_ProjectDir and
    " possibly b:atp_MainFile variables, it is not yet done.
    if filereadable(fnamemodify(expand(a:fname), ":r").".tex")
	setl nomodifiable
	setl buftype=nowrite
	setl nospell
	setl syn=log_atp
	setl autoread
	setl autowriteall
	nnoremap <silent> <buffer> ]m :call atplib#various#Search('\CWarning\\|^!', 'W')<CR>
	nnoremap <silent> <buffer> [m :call atplib#various#Search('\CWarning\\|^!', 'bW')<CR>
	nnoremap <silent> <buffer> ]w :call atplib#various#Search('\CWarning', 'W')<CR>
	nnoremap <silent> <buffer> [w :call atplib#various#Search('\CWarning', 'bW')<CR>
	nnoremap <silent> <buffer> ]c :call atplib#various#Search('\CLaTeX Warning: Citation', 'W')<CR>
	nnoremap <silent> <buffer> [c :call atplib#various#Search('\CLaTeX Warning: Citation', 'bW')<CR>
	nnoremap <silent> <buffer> ]r :call atplib#various#Search('\CLaTeX Warning: Reference', 'W')<CR>
	nnoremap <silent> <buffer> [r :call atplib#various#Search('\CLaTeX Warning: Reference', 'bW')<CR>
	nnoremap <silent> <buffer> ]e :call atplib#various#Search('^!', 'W')<CR>
	nnoremap <silent> <buffer> [e :call atplib#various#Search('^!', 'bW')<CR>
	nnoremap <silent> <buffer> ]f :call atplib#various#Search('\CFont \%(Info\\|Warning\)', 'W')<CR>
	nnoremap <silent> <buffer> [f :call atplib#various#Search('\CFont \%(Info\\|Warning\)', 'bW')<CR>
	nnoremap <silent> <buffer> ]p :call atplib#various#Search('\CPackage', 'W')<CR>
	nnoremap <silent> <buffer> [p :call atplib#various#Search('\CPackage', 'bW')<CR>
	nnoremap <silent> <buffer> ]P :call atplib#various#Search('\[\_d\+\zs', 'W')<CR>
	nnoremap <silent> <buffer> [P :call atplib#various#Search('\[\_d\+\zs', 'bW')<CR>
	nnoremap <silent> <buffer> ]i :call atplib#various#Search('\CInfo', 'W')<CR>
	nnoremap <silent> <buffer> [i :call atplib#various#Search('\CInfo', 'bW')<CR>
	nnoremap <silent> <buffer> % :call atplib#various#Searchpair('(', '', ')', 'W')<CR>
 
	call atplib#ReadATPRC()
	if !exists("g:atp_LogStatusLine")
	    let g:atp_LogStatusLine = 1
	endif
	if g:atp_LogStatusLine
	    let atplog_StatusLine = '%<%f %(%h%m%r%) %*%=  %-14.16(%l,%c%V%)%P'
	    let &statusline=atplog_StatusLine
	endif
	let b:atp_ProjectDir = expand("%:p:h")
	let b:atp_MainFile   = expand("%:p:r").".tex" 
	if !exists("g:atp_debugST")
	    let g:atp_debugST = 0
	endif
	if !exists("g:atp_LogSync")
	    let g:atp_LogSync = 0
	endif
	if !exists("b:atp_Viewer")
	    let b:atp_Viewer = "xpdf"
	endif
	if !exists("b:atp_XpdfServer")
	    let b:atp_XpdfServer = fnamemodify(b:atp_MainFile,":t:r")
	endif
	if !exists("g:atp_SyncXpdfLog")
	    let g:atp_SyncXpdfLog 	= 0
	endif
	if !exists("g:atp_TempDir")
	    call atplib#TempDir()
	endif
	if !exists("g:atp_tex_extensions")
	    let g:atp_tex_extensions	= ["tex.project.vim", "aux", "_aux", "log", "bbl", "blg", "bcf", "run.xml", "spl", "snm", "nav", "thm", "brf", "out", "toc", "mpx", "idx", "ind", "ilg", "maf", "glo", "mtc[0-9]", "mtc1[0-9]", "pdfsync", "synctex.gz" ]
	endif
	if !exists("b:atp_OutDir")
	    let b:atp_OutDir = substitute(fnameescape(fnamemodify(resolve(expand("%:p")),":h")) . "/", '\\\s', ' ' , 'g')
	endif
	if !exists("b:atp_TempDir")
	    let b:atp_TempDir = substitute(b:atp_OutDir . "/.tmp", '\/\/', '\/', 'g')
	endif
	command! -buffer -bang SyncTex	:call atplib#various#SyncTex(<q-bang>)
	nnoremap <buffer> <Enter>		:<C-U>SyncTex<CR>
	nnoremap <buffer> <LocalLeader>f	:<C-U>SyncTex<CR>	
	augroup ATP_SyncLog
	    au!
	    au CursorMoved *.log :call atplib#various#SyncTex("", 1)
	augroup END

	command! -buffer SyncXpdf 	:call atplib#various#SyncXpdfLog(0)
	command! -buffer Xpdf 	:call atplib#various#SyncXpdfLog(0)
	map <buffer> <silent> <F3> 	:<C-U>SyncXpdf<CR>
	augroup ATP_SyncXpdfLog
	    au CursorMoved *.log :call atplib#various#SyncXpdfLog(1)
	augroup END
    endif
endfunction
augroup ATP_texlog "{{{1
    au!
    au BufEnter *.log call <SID>TexLogSettings(expand("<afile>:p"))
augroup END
" Commands: "{{{1
command! -bang	UpdateATP				:call atplib#various#UpdateATP(<q-bang>)
command! 	ATPversion				:echo atplib#various#ATPversion()

" With bang: add most of the packages loaded in the current preambule. Also
" sets --tex (-t) and --class (-c) texdef option. Without bang only the --tex
" (-t) option is set ('tex', 'latex', 'contex', 'xelatex', 'lualatex', ...) 
" NOTE: only the first three are supported.
command! -bang -nargs=* TexDef :call atplib#tools#TexDef(<q-bang>,<q-args>)
syntax/bibsearch_atp.vim	[[[1
100
" Title:	Vim syntax file
" Author:	Bernd Feige <Bernd.Feige@gmx.net>
" Modified:	Marcin Szamotulski
" Note:		This file is a part of Automatic Tex Plugin for Vim.
" URL:		https://launchpad.net/automatictexplugin

" This is a modification of the standard syntax/bib.vim

" Initialization
" ==============
" For version 5.x: Clear all syntax items
" For version 6.x: Quit when a syntax file was already loaded
if version < 600
  syntax clear
elseif exists("b:current_syntax")
  finish
endif
" First we source syntax/bib.vim file
execute "source " . fnameescape("$VIMRUNTIME/syntax/bib.vim")
" Ignore case
syn case ignore

" Keywords
" ========
syn keyword bibsearchType contained	article book booklet conference inbook
syn keyword bibsearchType contained	incollection inproceedings manual
syn keyword bibsearchType contained	mastersthesis misc phdthesis
syn keyword bibsearchType contained	proceedings techreport unpublished
syn keyword bibsearchType contained	string
syn keyword bibsearchEntryKw contained	address author booktitle annote chapter
syn keyword bibsearchEntryKw contained	crossref edition editor issn howpublished
syn keyword bibsearchEntryKw contained	institution fjournal journal key month mrclass 
syn keyword bibsearchEntryKw contained	note number organization pages publisher
syn keyword bibsearchEntryKw contained	school series type title volume year
" Non-standard:
syn keyword bibsearchNSEntryKw contained	abstract isbn issn keywords url

" Clusters
" ========
syn cluster bibsearchVarContents	contains=bibsearchUnescapedSpecial,bibsearchBrace,bibsearchParen
" This cluster is empty but things can be added externally:
"syn cluster bibsearchCommentContents

" Matches
" =======
syn match bibsearchUnescapedSpecial contained /[^\\][%&]/hs=s+1
syn match bibsearchKey contained /\s*[^ \t}="]\+,/hs=s,he=e-1 nextgroup=bibsearchField
syn match bibsearchVariable contained /[^{}," \t=]/
syn region bibsearchQuote contained start=/"/ end=/"/  contains=@bibsearchVarContents
syn region bibsearchBrace contained start=/{/ end=/}/  contains=@bibsearchVarContents
syn region bibsearchParen contained start=/(/ end=/)/  contains=@bibsearchVarContents
syn region bibsearchField contained start="\S\+\s*=\s*" end=/[}),]/me=e-1 contains=bibsearchEntryKw,bibsearchNSEntryKw,bibsearchBrace,bibsearchParen,bibsearchQuote,bibsearchVariable
syn region bibsearchEntryData contained start=/[{(]/ms=e+1 end=/[})]/me=e-1 contains=bibsearchKey,bibsearchField
" Actually, 5.8 <= Vim < 6.0 would ignore the `fold' keyword anyway, but Vim<5.8 would produce
" an error, so we explicitly distinguish versions with and without folding functionality:
if version < 600
  syn region bibsearchEntry start=/@\S\+[{(]/ end=/^\s*[})]/ transparent contains=bibsearchType,bibsearchEntryData nextgroup=bibsearchComment
else
  syn region bibsearchEntry start=/@\S\+[{(]/ end=/^\s*[})]/ transparent fold contains=bibsearchType,bibsearchEntryData nextgroup=bibsearchComment
endif
syn region bibComment2 start=/@Comment[{(]/ end=/^\s*@/me=e-1 contains=@bibsearchCommentContents nextgroup=bibsearchEntry

" Synchronization
" ===============
syn sync match All grouphere bibsearchEntry /^\s*@/
syn sync maxlines=200
syn sync minlines=50

" Bibsearch
" =========
syn region bibsearchComment start=/./ end=/\s*@/me=e-1 contains=@bibsearchCommentContents,@bibsearchSearchInfo nextgroup=bibsearchEntry
syn region bibsearchInfo start=/\s*\d/ end=/\s@/me=e-1 contained containedin=bibsearchComment

" Highlighting defaults
" =====================
" Define the default highlighting.
" For version 5.7 and earlier: only when not done already
" For version 5.8 and later: only when an item doesn't have highlighting yet
if version >= 508 || !exists("did_bib_syn_inits")
  if version < 508
    let did_bib_syn_inits = 1
    command -nargs=+ HiLink hi link <args>
  else
    command -nargs=+ HiLink hi def link <args>
  endif
  HiLink bibsearchType		bibType
  HiLink bibsearchEntryKw	bibEntryKw
  HiLink bibsearchNSEntryKw	bibNSEntryKw
  HiLink bibsearchKey		bibKey
  HiLink bibsearchVariable	bibVariable
  HiLink bibsearchUnescapedSpecial	bibUnescapedSpecial
  HiLink bibsearchComment	bibComment
  HiLink bibsearchComment2	bibsearchComment
  HiLink bibsearchQuote		bibQuote        
  HiLink bibsearchBrace		bibBrace        
  HiLink bibsearchParen		bibParen        
  HiLink bibsearchInfo		Number
  delcommand HiLink
endif
let b:current_syntax = "bibsearch"
syntax/labels_atp.vim	[[[1
16
" Title: 	Vim syntax file
" Author:	Marcin Szamotulski
" Note:		This file is a part of Automatic Tex Plugin for Vim.
" URL:		https://launchpad.net/automatictexplugin

syntax region 	atp_Label_Line start=/^/ end=/$/ transparent contains=atp_Label_CounterValue,atp_Label_Name,atp_Label_LineNr  oneline nextgroup=atp_Label_Section
syntax match 	atp_Label_CounterValue	/^\%(\d\%(\d\|\.\)*[[:alpha:]]\=\)\|\%(\C[IXVL]\+\)/ nextgroup=atp_Label_Counter,atp_Label_Name
syntax match 	atp_Label_Name 		/\s\S.*\ze(/ contains=atp_label_Counter
syntax match 	atp_Label_Counter	/\[\w\=\]/ contained
syntax match  	atp_Label_LineNr 	/(\d\+)/ nextgroup=atp_Label_LineNr
syntax match 	atp_Label_FileName 	/^\(\S\&\D\).*(\/[^)]*)$/	

hi link atp_Label_FileName 	Title
hi link atp_Label_LineNr 	LineNr
hi link atp_Label_Name 		Label
hi link atp_Label_Counter	Keyword
syntax/log_atp.vim	[[[1
123
" Tite: 	Syntax file for tex log messages
" Author: 	Marcin Szamotulski
" Note:		This file is a part of Automatic Tex Plugin for Vim.
" URL:		https://launchpad.net/automatictexplugin

syntax keyword texlogKeyword 		LuaTeX LaTeX2e Babel pdfTeXk pdfTeX Web2C pdflatex latex teTeX TeXLive ON OFF 

" There is a small bug with this: 
" syntax keyword texlogLatexKeyword	LaTeX 			contained

syntax match texlogBrackets		'(\|)\|{\|}\|\\@<!\[\|\\@<!\]\|<\|>'

syntax match texlogOpenOut		'\\openout\d\+'

syntax match texlogDate			'\%(\s\|<\)\zs\%(\d\d\=\s\w\w\w\s\d\d\d\d\s\d\d:\d\d\|\d\d\d\d\/\d\d\/\d\d\)\ze\%(\s\|>\|$\)' 	
syntax match texlogVersion		'\<\%(v\|ver\)\s*\d*\.\d*\w\>'

" keywords: obsolete, undefined, not available
syntax match texlogWarningKeyword	'o\n\?b\n\?s\n\?o\n\?l\n\?e\n\?t\n\?e\|u\n\?n\n\?d\n\?e\n\?f\n\?i\n\?n\n\?e\n\?d\|n\n\?o\n\?t\_s\+a\n\?v\n\?a\n\?i\n\?l\n\?a\n\?b\n\?l\n\?e' 

syntax match texlogLatexInfo		'LaTeX Info:' 		contains=NONE
syntax match texlogLatexFontInfo	'LaTeX Font Info:' 	contains=NONE
syntax match texlogEndInfo		'Output written on\s\+\%(\S\|\.\|\\\s\|\n\)*' contains=texlogOutputWritten,texlogFileName transparent
syntax match texlogOutputWritten	'Output written on' 	contained 
syntax match texlogPages		'\zs\_d\+\_s\+pages\ze,\_s*\_d\+\_s\+bytes'

syntax match texlogPath			'\%(\/\%(\w\|-\|\\.\|\s\|\n\)\+\)\+\%(\.\_w\+\ze\%($\|)\)\)\+'
syntax match texlogPathB		'\%(<\|{\|\n\=\)\%(\/\%(\w\|-\|\\.\|\s\|\n\)\+\)\+\%(\.\_w\+\ze\%($\|)\|\n\=\)\)\+\%(>\|}\)'
syntax match texlogFont			'\\\=\%(OT\d\|T\d\|OMS\|OML\|U\|OMX\|PD\d\)\n\?\%(\/\_w\+\)\+'
syntax match texlogFontB		'\%(OT\d\|T\d\|OMS\|OML\|U\|OMX\|PD\d\)\n\?+\_w\+'
syntax match texlogFontSize		'<\d\+\%(\.\d\+\)\?>'

syntax match texlogLatexWarning		'LaTeX Warning:' 	contains=NONE
" is visible in synstack but is not highlighted.
syntax match texlogLatexFontWarning	'LaTeX Font Warning:' 	contains=NONE

syntax match texlogPdfTeXWarning	'pdfTeX warning'	contains=NONE

syntax match texlogPackageWarning	'Package\s\+\_w\+\_s\+Warning'
syntax match texlogPackageInfo		'Package\s\+\_w\+\_s\+Info'

syntax match texlogError		'^!.*$' contains=texlogLineNr

syntax match texlogOverfullBox		'Overfull\_s\\[hv]box'
syntax match texlogUnderfullBox		'Underfull\_s\\[hv]box'
syntax match texlogTooWide		't\n\?o\n\?o\_sw\n\?i\n\?d\n\?e'
syntax match texlogMultiplyDefined	'm\n\?u\n\?l\n\?t\n\?i\n\?p\n\?l\n\?y\%(\_s\s\?\|\n\?-\n\?\)\n\?d\n\?e\n\?f\n\?i\n\?n\n\?e\n\?d'
syntax match texlogRedefining		'\cr\n\?e\n\?d\n\?e\n\?f\n\?i\n\?n\n\?i\n\?n\n\?g'
syntax match texlogRedeclaring		'\cr\n\?e\n\?d\n\?e\n\?c\n\?l\n\?a\n\?r\n\?i\n\?n\n\?g'
syntax match texlogSourceSpecials	'S\n\?o\n\?u\n\?r\n\?c\n\?e\_ss\n\?p\n\?e\n\?c\n\?i\n\?a\n\?l\n\?s'
syntax match texlogLineParsing		'%\n\?&\n\?-\n\?l\n\?i\n\?n\n\?e\_sp\n\?a\n\?r\n\?s\n\?i\n\?n\n\?g'
syntax match texlogEnabled		'e\n\?n\n\?a\n\?b\n\?l\n\?e\n\?d' 

syntax match texlogLineNr		'\%(^l\.\|\so\n\?n\_si\n\?n\n\?p\n\?u\n\?t\_sl\n\?i\n\?n\n\?e\_s*\)\_d\+\s\?\|\s\?a\n\?t\n\?\_sl\n\?i\n\?n\n\?e\n\?s\_s\+\_d\+--\_d\+\s\?'
syntax match texlogPageNr		'\[\_d\+\%(\_s*{[^}]*}\)\?\]\|\s\?o\n\?n\n?\_sp\n\?a\n\?g\n\?e\_s\_d\+'

syntax match texlogDocumentClass	'Document Class:\s\+\S*'
syntax match texlogPackage		'Package:\s\+\S*'
syntax match texlogFile			'File:\s\+\S*'
syntax match texlogFileName		'\/\zs\%(\w\|\\\s\|-\|\n\)\+\.\%(dvi\|pdf\|ps\)' contained
syntax match texlogCitation		'Citation\s\+\`[^']*\'' 	contains=texlogScope
syntax match texlogReference		'Reference\s\+\`[^']*\'' 	contains=texlogScope
syntax match texlogScope		'\%(^\|\s\)\%(\`\|\'\)\zs[^']*\ze\'\%($\|\s\|\.\)'

syntax match texlogFontShapes		'\Cfont shapes' 
syntax match texlogChapter		'Chapter\s\+\%(\d\|\.\)\+'

" syntax match texlogDelimiter		'(\|)'
"
" This works only with 'sync fromstart'.
" syntax region texlogBracket	start="(" skip="\\[()]"	end=")" transparent contains=texlogPath,texlogPathB,texlogLatexInfo,texlogFontInfo,texlogEndInfo,texlogOutputWritten,texlogLatexWarning,texlogLatexFontInfo,texlogLatexFontWarning,texlogPackageWarning,texlogPackageInfo,texlogError,texlogLineNr,texlogPageNr,texlogPackage,texlogDocumentClass,texlogFile,texlogCitation,texlogReference,texlogKeyword,texlogLatexKeyword,texlogScope,texlogFont,texlogFontB,texlogFontSize,texlogOverfullBox,texlogUnderfullBox,texlogTooWide,texlogRedefining,texlogRedeclaring,texlogDate,texlogVersion,texlogWarningKeyword,texlogPages,texlogFontShapes,texlogOpenOut,texlogPdfTeXWarning,texlogBrackets,texlogEndInfo,texlogFileName,texlogPages,texlogChapter,texlogMultiplyDefined,texlogEnabled
" 
" syntax sync fromstart 

hi def link texlogKeyword		Keyword
hi def link texlogLatexKeyword		Keyword
hi def link texlogBrackets		Special
hi def link texlogOpenOut		Statement
hi def link texlogWarningKeyword	Identifier
hi def link texlogPath			Include
hi def link texlogPathB			texlogPath

hi def link texlogLatexInfo 		String

hi def link texlogOutputWritten		String
hi def link texlogFileName		Identifier
hi def link texlogPages			Identifier
hi def link texlogChapter		String

hi def link texlogLatexFontInfo 	String
hi def link texlogLatexWarning 		Identifier
hi def link texlogLatexFontWarning 	Identifier
hi def link texlogPackageWarning	Identifier
hi def link texlogPdfTeXWarning		Identifier
hi def link texlogPackageInfo 		String
hi def link texlogError 		Error

hi def link texlogLineNr		Number
hi def link texlogPageNr		Number

hi def link texlogDocumentClass		String
hi def link texlogPackage		String
hi def link texlogFile			String
hi def link texlogCitation		String
hi def link texlogReference		String
hi def link texlogOverfullBox		Function
hi def link texlogUnderfullBox		Function
hi def link texlogTooWide		Function
hi def link texlogRedefining		Function
hi def link texlogRedeclaring		Function
hi def link texlogSourceSpecials	Keyword
hi def link texlogEnabled		Keyword
hi def link texlogLineParsing		Keyword
hi def link texlogMultiplyDefined	Function
hi def link texlogScope			Label 

hi def link texlogFont			Label
hi def link texlogFontB			Label
hi def link texlogFontSize		Label
hi def link texlogFontShapes		String

hi def link texlogDate			Number
hi def link texlogVersion		Number
syntax/toc_atp.vim	[[[1
31
" Title:	Vim syntax file
" Author:	Marcin Szamotulski
" Note:		This file is a part of Automatic Tex Plugin for Vim.
" URL:		https://launchpad.net/automatictexplugin

syntax match  atp_FileName /^\s*\D.*$/
syntax match  atp_LineNr /^\s*\d\+/ skipwhite nextgroup=atp_Number,atp_Abstract
syntax match  atp_Number /\t\%(\d\+\.\?\|\*\)\+/ms=b+1,me=e contained nextgroup=atp_SectionTitle,atp_SubSectionTitle 

syntax match atp_Abstract /\t\+\s\s\(\S\&\D\).*$/ 

syntax match  atp_Chapter /^\s*\d\+\t\+\%(\d\+\|\*\)\s.*/ contains=atp_LineNr,atp_Number,atp_ChapterTitle
" syntax region atp_ChapterTitle matchgroup=atp_ChapterTitle start=/\d\s\(\S\&\D\)/ms=e-1 end=/$/me=e contained oneline

syntax match  atp_Section /^\s*\d\+\t\+\(\d\+\.\d\+\|\s\{3,}\|\*\)\s.\+/ contains=atp_LineNr,atp_Number,atp_SectionTitle 
" syntax region atp_SectionTitle matchgroup=atp_SectionTitle start=/\d\s\t\@<!/ms=e+1,ms=e+1 end=/$/me=e contained oneline

syntax match  atp_SubSection /^\s*\d\+\t\+\(\d\+\.\d\+\.\d\+\|\s\{5,}\|\*\)\s.\+/ contains=atp_LineNr,atp_Number,atp_SubSectionTitle 
" syntax region atp_SubSectionTitle matchgroup=atp_SubSectionTitle start=/\d\s\t\@<!/ms=e+1,ms=e+1 end=/$/me=e contained oneline

hi link atp_FileName 	Title
hi link atp_LineNr 	LineNr
hi link atp_Number 	Number
hi link atp_Abstract 	Label
hi link atp_Chapter 	Label
hi link atp_Section 	Label 
hi link atp_SubSection 	Label

" hi link atp_ChapterTitle 	Title
" hi link atp_SectionTitle 	Title 
" hi link atp_SubsectionTitle 	Title
